 # Generate 40 Gaussian random integers in the range 50-100

How to generate 40 Gaussian random integers in the range 50-100?

Regards,
HY

Hi,

You can’t. Gaussian random numbers are in the infinite range -â to +â,
and they aren’t integers.

Best you can do is get approximately or nearly Gaussian
numbers that are limited to the range 50-100.

First, you have to decide what the mean and stardard deviation of the
numbers should be. Lets say you want a mean of exactly half way, 75, and
a standard deviation of 10. That means that:

• approximately 68% of your numbers will be between 65 and 85;

• approximately 95% of your numbers will be between 55 and 95;

• approximately 99.7% of your numbers will be between 45 and 105;

• approximately 99.994% of your numbers will be between 35 and 115;

and so on. So the first step is to generate Gaussian random numbers:

``````>>> from random import gauss
>>> values = [gauss(75, 10) for i in range(10)]
>>> print(values)
[61.23596221286689, 76.60587129908207, 51.6560837542098,
57.99047892069517, 70.08685500419143, 76.62651107343562,
66.4317029607017, 83.96234038824969, 67.58214182339955,
80.13707807636534]
``````

The second step: you have floats, not integers. So let’s round them off:

``````>>> values = [int(round(x)) for x in values]
>>> print(values)
[61, 77, 52, 58, 70, 77, 66, 84, 68, 80]
``````

Nice! But it was just luck that every one of those numbers was between
50 and 100. If I generated a million numbers instead of 10, I would
probably have about 1% (ten thousand) outside of that range.

So the third step is to filter out anything outside of that range:

``````values = [x for x in values if 50 <= x <= 100]
``````

We can put all of this into a single function:

``````def my_gauss():
# Almost Gaussian random integers between 50 and 100
x = -1
while not 50 <= x <= 100:
x = int(round(gauss(75, 10)))
return x

values = [my_gauss() for x in range(10)]``````

Thank you very much for your wonderful solution.

Regards,
HY