如果您有一个旧版本的numpy,并且由于某些原因不能升级,那么您建议的生成随机字节、将其视为int64并根据您所需的范围截断它们的解决方案应该同样有效-
*正如@moarningsun在下面指出的rk_random_uint64实际上使用了拒绝采样,但我仍然认为没有理由不用模来包装这些值。在import numpy as np
from scipy import stats
def randint64(low, high, size, seed=None):
# generate a string of random bytes
n = np.prod(size)
bytes = np.random.RandomState(seed).bytes(n * 8)
# view as an int64 array
ints = np.fromstring(bytes, np.int64, n).reshape(size)
ints %= np.int64(high - low) # truncate
ints += np.int64(low) # offset
return ints
imax = np.iinfo(np.int64).max
print(imax)
# 9223372036854775807
ints = randint64(0, imax, int(1E6), seed=0)
print(ints.max())
# 9223355891497906972
# test uniformity
print(stats.kstest(ints, stats.uniform(loc=0, scale=imax).cdf))
# KstestResult(statistic=0.00085961807556278469, pvalue=0.45082598256836681