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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With