使用 python 生成整数的均匀分布

generating uniform distribution of integeres with python

我尝试使用 python 在给定区间内生成随机整数的均匀分布(是否包含上限并不重要)。我使用下一段代码来这样做并绘制结果:

import numpy as np
import matplotlib.pyplot as plt
from random import randint

propsedPython = np.random.randint(0,32767,8388602)%2048
propsedPythonNoMod = np.random.randint(0,2048,8388602)
propsedPythonNoModIntegers = np.random.random_integers(0,2048,8388602)
propsedPythonNoModRandInt = np.empty(8388602)
for i in range(8388602):
    propsedPythonNoModRandInt[i] = randint(0,2048)

plt.figure(figsize=[16,10])
plt.title(r'distribution $\rho_{prop}$ off all the python simulated proposed indices')
plt.xlabel(r'indices')
plt.ylabel(r'$\rho_{prop}$')
plt.yscale('log')
plt.hist(propsedPython,bins=1000,histtype='step',label=r'np.random.randint(0,32767,8388602)%2048')
plt.hist(propsedPythonNoMod,bins=1000,histtype='step',label=r'np.random.randint(0,2048,8388602')
plt.hist(propsedPythonNoModIntegers,bins=1000,histtype='step',label=r'np.random.random_integers(0,2048,8388602)')
plt.hist(propsedPythonNoModRandInt,bins=1000,histtype='step',label=r'for i in range(8388602):propsedPythonNoModRandInt[i] = randint(0,2048)')
plt.legend(loc=0)

结果图是:有人能给我指出正确的方向,为什么这些尖峰出现在所有不同的情况下,或者给出一些建议使用哪个例程来获得均匀分布的随机整数?

非常感谢!

嗯...

我使用了新的 NumPy rng 工具,图表对我来说还不错。

代码

import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng()

N = 1024*500

hist = np.zeros(2048, dtype=np.int32)

q = rng.integers(0, 2048, dtype=np.int32, size=N, endpoint=False)

for k in range(0, N):
    hist[q[k]] += 1

x = np.arange(0, 2048, dtype=np.int32)

fig, ax = plt.subplots()
ax.stem(x, hist, markerfmt=' ')
plt.show()

和图表