Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I produce random numbers between two values with a Gaussian distribution

Very new to Python, doing some exercises in a book. I need to produce 800 random numbers between 200 and 600, with a Gaussian distribution. I've got this far:

x = pylab.zeros(800,float)
for x in range (0,800):
    y = random.gauss(550,30)

However, isn't this going to produce any number as long as all 800 fit the Gaussian distribution? I need them between a range of 200 to 600.

like image 465
Versace Avatar asked Dec 26 '22 00:12

Versace


1 Answers

A Gaussian distribution isn't bounded, but you can make it unlikely that you will sample outside your range. For example, you can sample numbers with a mean of 400 and a standard deviation of 200/3, meaning being outside the range [200, 600] will be outside of 3 standard deviations.

mean = 400
stdev = 200/3   # 99.73% chance the sample will fall in your desired range

values = [random.gauss(mean, stdev) for _ in range(800)]

If you want to have a bounded psuedo-Gaussian distribution you can do something like this

values = []
while len(values) < 800:
    sample = random.gauss(mean, stdev)
    if sample >= 200 and sample < 600:
        values.append(sample)

So if you sample a value outside of your desired range, you throw it out and resample.

like image 193
Cory Kramer Avatar answered Apr 06 '23 23:04

Cory Kramer