[Tutor] Generating random numbers

Tim Peters tim.one at comcast.net
Fri Dec 5 00:36:22 EST 2003


[Venkatesh Babu]
> Just wanted to clarify my point once again.
>
> So, do u mean to say that in a single thread, the
> following sequence of calls are OK:
>
> random.gauss(50, 5)
> random.gauss(50, 5)
> ... Some code....
> random.gauss(25, 4)
> random.gauss(25, 4)
> ... Some more code....
> random.gauss(50, 5)
> random.gauss(50, 5)

Yes, that's what I thought you meant, and it's fine.

> Because till now I was thinking that generation of
> random numbers following a probability distribution
> should maintain some history information.

Virtually all methods of generating random variates following a particular
distribution work by applying transformations to a uniform random float in
0.0 to 1.0.  For example, to generate a random float uniformly from 1 to 5,
take a random float uniformly from 0 to 1, multiply it by 4, then add 1.  It
doesn't need any history, it only needs to be given a uniform random float
in 0 to 1 to work with.

You can read the code in random.py to see that almost all the methods work
"like that".  Some are very subtle, and require difficult correctness proofs
if you *really* want to know how they work.

The gauss() method used by Python is briefly but nicely described here:

    http://en.wikipedia.org/wiki/Box-Muller_transform

That page shows how to generate random *unit* normal variates given a source
of random uniform variates in 0 to 1.  Dealing with arbitrary mu and sigma
is a trivial transformation beyond that (after you get it, multiply the
random unit normal variate by sigma, then add mu).  More detail can be found
here:

    http://www.taygeta.com/random/gaussian.html

As that page says <wink>,

    Finding transformations like the Box-Muller is a tedious process,
    and in the case of empirical distributions it is not possible.




More information about the Tutor mailing list