繁体   English   中英

用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()

和图

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM