I would like to choose a random seed for numpy.random
and save it to a variable. I can set the seed using numpy.random.seed(seed=None
) but how do you
According to the docs, when seed
is None
, numpy
tries to read from /dev/urandom
, so why not just read a value from /dev/urandom
, save it, and pass it to numpy.random.RandomState
?
EDIT:
The internal state can be get and set via get_state and set_state, respectively. So, to recover the initial state, one would do something like this:
>>> import numpy
>>> r = numpy.random.RandomState()
>>> saved_state = r.get_state()
>>> r.rand()
0.9091545657342729
>>> r.rand()
0.9677739782319564
>>> r.rand()
0.5656156400920441
>>> r.set_state(saved_state)
>>> r.rand()
0.9091545657342729
>>> r.rand()
0.9677739782319564
>>> r.rand()
0.5656156400920441
>>>
When seed is None
, numpy
doesn't pick a "new random seed" and call seed()
with it. It reads 624 * sizeof(long)
bytes (~ 2.5KB
) from /dev/urandom
and uses those values to populate the state
struct. When you call seed()
without arguments, numpy
never actually "chooses" a "random seed". Therefore, it's not possible to recover it.