使用 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屋!