Consider the MWE:
(the main idea is to choose a random point from a list and determine the farthest one from it):
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()
It appears to work well but some times, it gives an error, as below:
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
I really don't understand. In this case, r=5
and so the error since pts
index should be from 0
to 4
(remember N=5
).
But why r=5
was chosen since it was defined as r=randint(0,N)
?