Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify upper and lower limits when using numpy.random.normal

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 

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.

like image 995
Catherine Georgia Avatar asked Aug 26 '13 10:08

Catherine Georgia


People also ask

What are the three arguments for NP random normal ()?

The np. random. normal function has three primary parameters that control the output: loc , scale , and size .

What is normal distribution Numpy?

The normal distribution is a form presenting data by arranging the probability distribution of each value in the data. Most values remain around the mean value making the arrangement symmetric. We use various functions in numpy library to mathematically calculate the values for a normal distribution.

What does NP random uniform do?

uniform function. When we use Numpy random uniform, it creates a Numpy array that's filled with numeric values. Those numeric values are drawn from within the specified range, specified by low to high . The function will randomly select N values from that range, where N is given by the size parameter.


1 Answers

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() 

enter image description here

The top figure shows the truncated normal distribution, the lower figure shows the normal distribution with the same mean mu and standard deviation sigma.

like image 185
unutbu Avatar answered Sep 27 '22 21:09

unutbu