faqts : Computers : Programming : Languages : Python : Common Problems : Maths : Random Numbers

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

9 of 13 people (69%) answered Yes
Recently 5 of 6 people (83%) answered Yes

Entry

Is there any difference between the random number generator in the'random' module and that in the 'whrandom' one?
Is there a way to get a reproducible sequence of random numbers?
What's the quality of the numbers generated?

May 23rd, 2000 05:09
unknown unknown, Jim Richardson, Ivan Frohne


If I'm not mistaken, whrandom is imported by random, and importing
random would be the normal way of accessing it.

You shouldn't use whrandom:  whrandom is an interal implementation 
detail of random.py.  whrandom.py should probably be renamed to 
_whrandom.py (or something) to stop people from tripping over it.

Repeatable sequences can be generated by reseeding with the same value:

>>> import random
>>> random.seed("Spam")
>>> print random.random()
0.188524911272
>>> print random.random()
0.795451892756
>>> print random.random()
0.191986312458
>>> random.seed("Spam")
>>> print random.random()
0.188524911272
>>> print random.random()
0.795451892756
>>> print random.random()
0.191986312458

>>> print random.seed.__doc__
Seed the default generator from any hashable value.

  None or no argument returns (0, 0, 0) to seed from current time.

Regarding the quality:

If you know enough about random numbers to understand an answer to that
question, then telling you it's the standard Wichman-Hill (that's where 
"wh" comes from) generator is all the answer you need <wink>.  
Seriously, test it and determine whether it's adequate for your 
application; if you can't test it objectively, then you have no way of 
knowing whether any other package is adequate either (and neither does 
anyone else, so don't ask).

Ivan Frohne wrote a very nice package of stronger generators, which 
should be available from his Starship page.  But unless you're doing 
extreme work, WH should be adequate for a start.  Any serious program 
relying on random numbers should be tested with at least two distinct 
generators, though, and Ivan's pkg is great for that.

You can find the algorithm used in whrandom.py and random.py (in Fortran 
77) at http://lib.stat.cmu.edu/apstat/183 .  It was published in the 
Journal of Applied Statistics in 1982, and is now a little long in the 
tooth.  The period is about 7e12, which you might think is large, but, 
when you get right down to it, it's not large enough.  In fact, an 
alternative algorithm with period 2e18 is now recommended at the site 
listed above. But the truth of the matter is, random.py will give you 
perfectly fine uniform random numbers for most purposes, if you're not 
too fussy, and don't need hundreds of millions of them.

As an aside, for those using linux, then /dev/random and /dev/urandom
are good reseources for (very nearly) random numbers.