Generating numbers with Gaussian function in a range using python

Lily picture Lily · May 9, 2013 · Viewed 32.7k times · Source

I want to use the gaussian function in python to generate some numbers between a specific range giving the mean and variance

so lets say I have a range between 0 and 10

and I want my mean to be 3 and variance to be 4

mean = 3, variance = 4

how can I do that ?

Answer

Dan Lecocq picture Dan Lecocq · May 9, 2013

Use random.gauss. From the docs:

random.gauss(mu, sigma)
    Gaussian distribution. mu is the mean, and sigma is the standard deviation. This is slightly
    faster than the normalvariate() function defined below.

It seems to me that you can clamp the results of this, but that wouldn't make it a Gaussian distribution. I don't think you can satisfy all the constraints simultaneously. If you want to clamp it to the range [0, 10], you could get your numbers:

num = min(10, max(0, random.gauss(3, 4)))

But then the resulting distribution of numbers won't be truly Gaussian. In this case, it seems you can't have your cake and eat it, too.