python - How to specify upper and lower limits when using numpy.random.normal -
iok want able pick values normal distribution ever fall between 0 , 1. in cases want able return random distribution, , in other cases want return values fall in shape of gaussian.
at moment using following function:
def blockedgauss(mu,sigma): while true: numb = random.gauss(mu,sigma) if (numb > 0 , numb < 1): break return numb
it picks value normal distribution, discards if falls outside of range 0 1, feel there must better way of doing this.
it sounds want truncated normal distribution. using scipy, use scipy.stats.truncnorm
generate random variates such distribution:
import matplotlib.pyplot plt import scipy.stats 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()
the top figure shows truncated normal distribution, lower figure shows normal distribution same mean mu
, standard deviation sigma
.
Comments
Post a Comment