使用numpy.random.normal时如何指定上限和下限 [英] How to specify upper and lower limits when using numpy.random.normal
问题描述
我希望能够从仅介于0到1之间的正态分布中选择值.在某些情况下,我希望能够基本上只返回完全随机的分布,而在其他情况下,我希望返回值呈高斯形状.
I want to be able to pick values from a normal distribution that only ever fall between 0 and 1. In some cases I want to be able to basically just return a completely random distribution, and in other cases I want to return values that fall in the shape of a gaussian.
此刻我正在使用以下功能:
At the moment I am using the following function:
def blockedgauss(mu,sigma):
while True:
numb = random.gauss(mu,sigma)
if (numb > 0 and numb < 1):
break
return numb
它从正态分布中选择一个值,如果该值不在0到1的范围内,则将其丢弃,但是我觉得必须有一种更好的方法.
It picks a value from a normal distribution, then discards it if it falls outside of the range 0 to 1, but I feel like there must be a better way of doing this.
推荐答案
听起来您想要被截断的普通分布.
使用scipy,您可以使用scipy.stats.truncnorm
从这种分布生成随机变量:
It sounds like you want a truncated normal distribution.
Using scipy, you could use scipy.stats.truncnorm
to generate random variates from such a distribution:
import matplotlib.pyplot as plt
import scipy.stats as stats
lower, upper = 3.5, 6
mu, sigma = 5, 0.7
X = stats.truncnorm(
(lower - mu) / sigma, (upper - mu) / sigma, loc=mu, scale=sigma)
N = stats.norm(loc=mu, scale=sigma)
fig, ax = plt.subplots(2, sharex=True)
ax[0].hist(X.rvs(10000), normed=True)
ax[1].hist(N.rvs(10000), normed=True)
plt.show()
上面的图显示了正态分布的截断,下面的图显示了均值mu
和标准差sigma
相同的正态分布.
The top figure shows the truncated normal distribution, the lower figure shows the normal distribution with the same mean mu
and standard deviation sigma
.
这篇关于使用numpy.random.normal时如何指定上限和下限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!