0

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)?

Sigur
  • 355
  • 8
  • 19
  • 1
    `r=randint(0,N-1)` – Jake Nov 02 '17 at 00:49
  • 1
    **What a shame!** From doc I got *`random.randint(a, b)` Return a random integer N such that a <= N <= b.* So, I mixed with the one from `numpy` which is exclusive, ie, less than `b`. It would be good to have the same output. Sorry. I'll delete. – Sigur Nov 02 '17 at 00:51
  • @Sigur: If you're using the non-`numpy` `random` module, for exclusivity on the high end you'd want `random.randrange`. – ShadowRanger Nov 02 '17 at 00:54

2 Answers2

1

Looking at the manual:

random.randint(a, b)
    Return a random integer N such that a <= N <= b. Alias for randrange(a, b+1).

What you maybe want to use is numpy.random.randint:

numpy.random.randint(low, high=None, size=None, dtype='l')
[...]
    high : int, optional
      If provided, one above the largest (signed) integer to be drawn from the
      distribution (see above for behavior if high=None).

This will give you your expected behaviour.

Ken Y-N
  • 14,644
  • 21
  • 71
  • 114
0

you should replace

P0 = pts[r]

by

P0 = pts[r-1]

since list are indexed from 0 to size-1! Or you can also adapt the range of the randint to

r=randint(0,N-1)

As you prefer.

Last but not least, the error means that you are trying to access a cell of you array that is out of bound:

IndexError: list index out of range

Hope it helps you!

Allan
  • 12,117
  • 3
  • 27
  • 51