6

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.

cholo14
  • 594
  • 1
  • 3
  • 22
Versace
  • 175
  • 1
  • 3
  • 11
  • 3
    If you limit the values it's not a Gaussian distribution any longer. – Matthias Jan 08 '15 at 13:29
  • How would I get it to follow that shape then, so that 400 would be the number that occurs the most? – Versace Jan 08 '15 at 13:31
  • You could check whether y is between 200 and 600. Not very clean but still simple – Vincent Beltman Jan 08 '15 at 13:31
  • A Gaussian distribution with mean 550 and deviation 30 is very-very unlikely to give you numbers over 800, but it is still possible. You can check explicitly to filter invalid values. – leeladam Jan 08 '15 at 13:31

2 Answers2

11

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.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
2

I think the best way would be to generate a Gaussian distribution and then re-scale all the values so that max=600 and min=200.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
anyom
  • 21
  • 1