【问题标题】:Why python randint(0,N) returns N? [duplicate]为什么 python randint(0,N) 返回 N? [复制]
【发布时间】: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 索引应该是从04(记住N=5)。

但是既然r=5被定义为r=randint(0,N),为什么还要选择它呢?

【问题讨论】:

  • r=randint(0,N-1)
  • 真可惜!我从文档中得到 random.randint(a, b) 返回一个随机整数 N,使得 a 所以,我混合了来自numpy 的那个是排他的,即小于b。最好有相同的输出。对不起。我会删除。
  • @Sigur:如果你使用非numpy random 模块,那么你会想要random.randrange 的高端排他性。

标签: python-2.7


【解决方案1】:

at the manual:

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

你可能想要使用的是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).

这将为您提供预期的行为。

【讨论】:

    【解决方案2】:

    你应该替换

    P0 = pts[r]
    

    P0 = pts[r-1]
    

    因为列表的索引是从 0 到 size-1! 或者您也可以将 randint 的范围调整为

    r=randint(0,N-1)
    

    随你喜欢。

    最后但并非最不重要的一点是,该错误意味着您正在尝试访问超出范围的数组单元:

    IndexError: list index out of range
    

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-19
      • 1970-01-01
      • 2015-05-04
      • 1970-01-01
      • 2017-06-13
      • 1970-01-01
      • 2020-09-23
      相关资源
      最近更新 更多