How Python visits Mersenne twister

How does Python seed its Mersenne twister pseudo-random number generator? Is it somehow based on a watch? If so, is the seed detected when importing a random module or when it is first called?

The Python documentation does not seem to be responding.

+4
source share
3 answers

The seed is based on the clock or (if available) the source of the operating system. The random module creates (and therefore seeds) a common random instance when it is imported, and not the first time it is used.

References

Python docs for random.seed :

 random.seed(a=None, version=2) 

Initialize the random number generator.

If a is omitted or None, the current system time is used. If sources of randomness are provided by the operating system, they are used instead of system time (see the os.urandom () function for details on availability).

Source random.py (heavily cut off):

 from os import urandom as _urandom class Random(_random.Random): def __init__(self, x=None): self.seed(x) def seed(self, a=None, version=2): if a is None: try: a = int.from_bytes(_urandom(32), 'big') except NotImplementedError: import time a = int(time.time() * 256) # use fractional seconds # Create one instance, seeded from current time, and export its methods # as module-level functions. The functions share state across all uses #(both in the user code and in the Python libraries), but that fine # for most programs and is easier for the casual user than making them # instantiate their own Random() instance. _inst = Random() 

The last line is at the top level, so it runs when the module loads.

+2
source

In modern versions of python (cf http://svn.python.org/projects/python/branches/release32-maint/Lib/random.py ) Random.seed tries to use 32 bytes read from / dev / urandom. If this does not work, it uses the current time: ( a is an optional value that can be used to explicitly allocate 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 
+3
source

From this answer, I found the source random.py. In the Random class, the seed is set when constructing an object. The module creates an instance of the Random object and uses it for all methods of the module. Therefore, if a random number is created using random.random() or another module method, then the seed was set during import. If a random number is created by another instance of Random, then the seed was set during the construction of this instance.

From source:

 # Create one instance, seeded from current time, and export its methods # as module-level functions. The functions share state across all uses #(both in the user code and in the Python libraries), but that fine # for most programs and is easier for the casual user than making them # instantiate their own Random() instance. 
+2
source

Source: https://habr.com/ru/post/1491298/


All Articles