获取一个标准差以内的随机数

Get random numbers within one standard deviation

我想生成随机数,比如说 100。现在我使用 numpy 的目的如下:

print numpy.random.normal(loc=200,scale=50,size=100)

但我希望生成的数字仅与平均值相差一个标准差,即 loc。最好的方法是什么?

我应该简单地做类似的事情吗:

print numpy.random.randint(150, high=250, size=100)

或者还有其他方法吗?

选一个号码

按照@Robert Kern's use scipy's truncnorm

中的建议
from scipy import stats

arr = stats.truncnorm.rvs(-1, 1, loc=200.0, scale=50.0, size=1) 
print(arr[0])     

前两个参数表示范围[a,b](以标准差衡量),loc是均值(分布的中心),scale是标准差(分布的分布情况)。

在 -1 到 +3 STD 范围内绘制数字

import matplotlib.pyplot as plt
from scipy import stats

# -1 to +3 standard deviations apart
r = stats.truncnorm.rvs(-1, 3, loc=200.0, scale=50.0, size=10**6)

plt.hist(r, bins=100, color='blue')
plt.xlabel("value")
plt.ylabel("frequency")
plt.show()


旁注: randint()normal() 而不是 以相同的方式选择号码。

numpy.random.randint

Return random integers from the “discrete uniform” distribution in the “half-open” interval.

numpy.random.normal

Draw random samples from a normal (Gaussian) distribution.

使用 randint() 在所选区间内获得任何数字的几率是相同的,这与 normal distribution 中的数字不同(获得更接近峰值的数字的几率更大)。