问题描述
与np.random.randint()
一样如何生成随机整数,但正态分布在0附近.
How to generate a random integer as with np.random.randint()
, but with a normal distribution around 0.
np.random.randint(-10, 10)
返回具有离散均匀分布的整数np.random.normal(0, 0.1, 1)
返回具有正态分布的浮点数
np.random.randint(-10, 10)
returns integers with a discrete uniform distributionnp.random.normal(0, 0.1, 1)
returns floats with a normal distribution
我想要的是两种功能之间的一种组合.
What I want is a kind of combination between the two functions.
推荐答案
获得正态分布看起来像的离散分布的另一种可能方法是从概率为从正态分布计算得出.
One other possible way to get a discrete distribution that looks like the normal distribution is to draw from a multinomial distribution where the probabilities are calculated from a normal distribution.
import scipy.stats as ss
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-10, 11)
xU, xL = x + 0.5, x - 0.5
prob = ss.norm.cdf(xU, scale = 3) - ss.norm.cdf(xL, scale = 3)
prob = prob / prob.sum() #normalize the probabilities so their sum is 1
nums = np.random.choice(x, size = 10000, p = prob)
plt.hist(nums, bins = len(x))
在这里,np.random.choice
从[-10,10]中选择一个整数.通过p(-0.5 <x <0.5)来计算选择元素(例如0)的概率,其中x是均值为零且标准差为3的正态随机变量.开发.之所以设为3,是因为p(-10
Here, np.random.choice
picks an integer from [-10, 10]. The probability for selecting an element, say 0, is calculated by p(-0.5 < x < 0.5) where x is a normal random variable with mean zero and standard deviation 3. I chooce std. dev. as 3 because this way p(-10 < x < 10) is almost 1.
结果如下:
这篇关于如何生成整数的随机正态分布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!