Random Number Generation?

Bengt Richter bokr at oz.net
Mon Dec 12 03:33:57 CET 2005


On Sun, 11 Dec 2005 09:46:33 -0800 (PST), Dimos <dimos_anastasiou at yahoo.com> wrote:

>Hello All,
>
>I need some help with random number generation. What I
>need exactly is:
>
>To create a few thousand numbers, decimal and
>integers, between 5 and 90, 
>and then to export them as a single column at a
>spreadsheet.
>
>I am newbie, I was not able to create decimals with
>the random modules of 
>Python 2.3.
>
Others have mentioned random.random and, better for your use case,
random.uniform, but I'm not sure what you mean by "decimal and integers".

Theoretically, the chances of getting an integer from a uniformly random
sample from an interval of real numbers is practically zero, and even
allowing for IEEE 754 double representation, the realtive population of
integers vs non-integers is pretty low. So what do you mean by "integer"?
And what by "decimals"?

If you just want an artificial sprinkling of exact integer values to
happen some percentage of the time, you could do something like

 >>> from random import uniform, random
 >>> def urnmix(nnum=20, lo=5, hi=90, percentint=25):
 ...     percentint /= 100.
 ...     for _ in xrange(nnum):
 ...         u = uniform(5, 90)
 ...         if random()<percentint: u = round(u)
 ...         yield u
 ...
 >>> for u in urnmix(12): print '%6.3f'%u,
 ...
  9.000 38.173 59.829 37.090 80.504 34.000 69.989 26.000 72.502 64.000 55.000  9.043
 >>> for u in urnmix(12): print '%6.3f'%u,
 ...
 10.000 67.687 70.323 66.672 17.150 68.447 84.406  6.997 82.444  8.001 82.946 34.849
 >>> for u in urnmix(12): print '%6.3f'%u,
 ...
 70.000 64.000 36.537 75.270 67.000 70.873 28.446 18.483 75.086 41.703 82.885 30.558
 >>> for u in urnmix(12): print '%6.3f'%u,
 ...
 75.000 78.313 76.873 48.364 12.000 40.000 36.962 27.704  8.814 44.078 61.000 35.654
 >>>

Hm, let's check the percentages

 >>> [u==int(u) for u in urnmix(12)]
 [True, False, False, False, False, True, True, True, True, False, True, False]
 >>> [u==int(u) for u in urnmix(12)].count(True)
 2
 >>> [u==int(u) for u in urnmix(12)].count(True)
 4
 >>> [u==int(u) for u in urnmix(10000)].count(True)
 2471
 >>> [u==int(u) for u in urnmix(10000)].count(True)
 2539
 
Seems to work ...

 >>> [u==int(u) for u in urnmix(10000, 5, 90, 5)].count(True)
 497
 >>> [u==int(u) for u in urnmix(10000, 5, 90, 1)].count(True)
 111
 >>> [u==int(u) for u in urnmix(10000, 5, 90, 1)].count(True)
 87
 >>> [u==int(u) for u in urnmix(10000, 5, 90, 1)].count(True)
 113

After all this playing, what was it you actually wanted? ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list