I know how to set the random seed in python
random.seed([x])
Once the seed is set is there any way to read it back and figure out what value was passed to the seed() function?
I know how to set the random seed in python
random.seed([x])
Once the seed is set is there any way to read it back and figure out what value was passed to the seed() function?
While the underlying algorithm for Python's Random (Mersenne Twister) is deterministic, the seed is not stored anywhere in the implementation's memory space. It is up to the caller to store the seed, if necessary.
http://docs.python.org/library/random.html#module-random
For more info on Python's implementation (or to override it with your own seed storing random class) see:
http://hg.python.org/cpython/file/0b650272f58f/Lib/random.py
and
http://hg.python.org/cpython/file/0b650272f58f/Python/random.c
There is no way to get back the seed itself. The seed is used to update the internal state of the random number generator, and it is not directly stored anywhere.
There is a way however, to save the current state! The random module is based on the Mersenne Twister pseudo random number generator, and it is implemented in C (with the _random extension module). You can do this:
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 the __getstate__
/ __setstate__
methods directly) to go back to a previous state.