numpy,如何生成一组正态分布的整数

时间:2015-10-15 23:49:29

标签: python numpy statistics scipy

使用numpy生成正态分布的整数集的最佳方法是什么?我知道我可以用这样的东西得到漂浮物:

In [31]: import numpy as np

In [32]: import matplotlib.pyplot as plt

In [33]: plt.hist(np.random.normal(250, 1, 100))
Out[33]: 
(array([  2.,   5.,   9.,  10.,  19.,  21.,  13.,  10.,   6.,   5.]),
 array([ 247.52972483,  247.9913017 ,  248.45287858,  248.91445546,
         249.37603233,  249.83760921,  250.29918608,  250.76076296,
         251.22233984,  251.68391671,  252.14549359]),
 <a list of 10 Patch objects>)

histogram

2 个答案:

答案 0 :(得分:5)

Binomial Distribution是正态分布的良好离散近似。即,

Binomial(n, p) ~ Normal(n*p, sqrt(n*p*(1-p)))

所以你可以做到

import numpy as np
import matplotlib.pyplot as plt
from math import sqrt

bi = np.random.binomial(n=100, p=0.5, size=10000)
n = np.random.normal(100*0.5, sqrt(100*0.5*0.5), size=10000)

plt.hist(bi, bins=20, normed=True);
plt.hist(n, alpha=0.5, bins=20, normed=True);
plt.show();

enter image description here

答案 1 :(得分:2)

稍后会遇到这个问题,但是如果你想生成一个任意分布的整数集,请使用相反分布的逆CDF(百分位数),例如,scipy.stats并统一绘制百分位数从中。然后只需转换为整数即可完成:

from scipy.stats import norm
import matplotlib.pyplot as plt
# Generate 1000 normal random integers with specified mean and std.
draw = norm.ppf(np.random.random(1000), loc=mean, scale=std).astype(int)
plt.hist(draw)

continuous distributions in scipy.stats can be found here列表以及discrete distributions can be found here列表。

对于上面的例子,您可以直接从您想要的分布中绘制并转换为整数,但这种方法的好处(从CDF统一采样百分位数)是它适用于任何分布,甚至是你只能用数据来定义数字!