【发布时间】:2018-04-14 10:04:33
【问题描述】:
考虑 MWE:
(主要思想是从一个列表中选择一个随机点,并确定离它最远的那个):
import numpy as np
import matplotlib.pyplot as plt
from random import randint
from scipy.spatial.distance import euclidean
N = 5 # number of points
print( 'N = %d' % N)
x=[ randint(1,N) for p in range(0,N)]
y=[ randint(1,N) for p in range(0,N)]
pts = [[x[i],y[i]] for i in range(0,N)]
print pts
def dist_ponto_lista(ponto,lista):
return [ euclidean(ponto,lista[j]) for j in range(len(lista)) ]
def ponto_mais_longe(lista_ds):
ds_max = max(lista_ds)
idx = lista_ds.index(ds_max)
return pts[idx]
r=randint(0,N)
print r
P0 = pts[r] # choose a random pt from pts
ds = dist_ponto_lista(P0,pts)
PML = ponto_mais_longe(ds)
print P0
print ds
print PML
quit()
它似乎运行良好,但有时会出错,如下所示:
N = 5 [[5, 4], [3, 2], [5, 3], [4, 2], [1, 1]] 5 Traceback (most recent call last): File "farthest-pts.py", line 25, in <module> P0 = pts[r] IndexError: list index out of range ------------------ (program exited with code: 1) Press return to continue
我真的不明白。在这种情况下,r=5 等错误因为pts 索引应该是从0 到4(记住N=5)。
但是既然r=5被定义为r=randint(0,N),为什么还要选择它呢?
【问题讨论】:
-
r=randint(0,N-1) -
真可惜!我从文档中得到
random.randint(a, b)返回一个随机整数 N,使得 a 所以,我混合了来自numpy的那个是排他的,即小于b。最好有相同的输出。对不起。我会删除。 -
@Sigur:如果你使用非
numpyrandom模块,那么你会想要random.randrange的高端排他性。
标签: python-2.7