Random and Pseudorandom Numbers
The random
module of the standard Python library generates pseudorandom numbers with various distributions. The underlying uniform pseudorandom generator uses the Mersenne Twister algorithm, with a period of length 2**19937-1
. (Older versions of Python used the Whichmann-Hill algorithm, with a period of length 6,953,607,871,644.)
Physically random and cryptographically strong random numbers
Pseudorandom numbers provided by module random
, while very good, are not of cryptographic quality. If you want higher-quality random numbers (ideally, physically generated random numbers rather than algorithmically generated pseudorandom numbers), in Python 2.4, you can call os.urandom
(from module os
, not random
).
urandom |
Returns |
For an alternative source of physically random numbers, see http://www.fourmilab.ch/hotbits.
The random module
All functions of module random
are methods of one hidden global instance of class random.Random
. You can instantiate Random
explicitly to get multiple generators that do not share state. Explicit instantiation is advisable if you require random numbers in multiple threads (threads are covered in Chapter 14). This section documents the most frequently ...
Get Python in a Nutshell, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.