numpy如何生成一个正态分布的整数集合

2024-03-29 07:01:45 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 方法inimportnumpymatplotlibasnpplt
2条回答

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

过了很长一段时间后才发现这一点,但如果要生成任意分布的整数集,请使用反向CDF(percentile)作为来自^{}的关联分布,并从中均匀地绘制百分位数。然后转换成整数,就完成了:

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 ^{} can be found here的列表和discrete distributions can be found here的列表。

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

相关问题 更多 >