Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Python seed the Mersenne twister

Tags:

python

random

How does Python seed its Mersenne twister pseudorandom number generator used in the built-in random library if no explicit seed value is provided? Is it based on the clock somehow? If so, is the seed found when the random module is imported or when it is first called?

Python's documentation does not seem to have the answer.

like image 554
Guido Salducci Avatar asked Jul 14 '13 03:07

Guido Salducci


1 Answers

In modern versions of python (c.f. http://svn.python.org/projects/python/branches/release32-maint/Lib/random.py) Random.seed tries to use 32 bytes read from /dev/urandom. If that doesn't work, it uses the current time: (a is an optional value which can be used to explicitly seed the PRNG.)

    if a is None:
        try:
            a = int.from_bytes(_urandom(32), 'big')
        except NotImplementedError:
            import time
            a = int(time.time() * 256) # use fractional seconds
like image 122
bks Avatar answered Oct 22 '22 22:10

bks