Is there a way to read random seed in python?

I know how to set random seed in python

random.seed([x])

Once the seed is established, is there a way to read it and find out what value was passed to the seed () function?

+4
source share
2 answers

Although the basic algorithm for Python Random (Mersenne Twister) is deterministic, the seed is not stored anywhere in the implementation's memory space. If necessary, the caller can store the seeds.

http://docs.python.org/library/random.html#module-random

For more information on the Python implementation (or to override it using native seed storage of a random class), see

http://hg.python.org/cpython/file/0b650272f58f/Lib/random.py

and

http://hg.python.org/cpython/file/0b650272f58f/Python/random.c

+4
source

It is impossible to return the seed itself. The seed is used to update the internal state of the random number generator, and it is not stored anywhere.

However, there is a way to keep the current state! The random module is based on the Mersenne Twister pseudo random number generator, and it is implemented in C (with an extension module). You can do it:

 import random r = random.Random() # Use the r object to generate numbers # ... curstate = r.__getstate__() # Use it even more.. # r.__setstate__(curstate) # Go back to previous state 
In other words, random.Random () objects can be pickled, and you can use pickled objects (or __getstate__ / __setstate__ ) to return to the previous state.
+3
source

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


All Articles