Search code examples
pythonnumpyrandomrandom-seedmersenne-twister

How can I retrieve the current seed of NumPy's random number generator?


The following imports NumPy and sets the seed.

import numpy as np
np.random.seed(42)

However, I'm not interested in setting the seed but more in reading it. random.get_state() does not seem to contain the seed. The documentation doesn't show an obvious answer.

How do I retrieve the current seed used by numpy.random, assuming I did not set it manually?

I want to use the current seed to carry over for the next iteration of a process.


Solution

  • The short answer is that you simply can't (at least not in general).

    The Mersenne Twister RNG used by numpy has 219937-1 possible internal states, whereas a single 64 bit integer has only 264 possible values. It's therefore impossible to map every RNG state to a unique integer seed.

    You can get and set the internal state of the RNG directly using np.random.get_state and np.random.set_state. The output of get_state is a tuple whose second element is a (624,) array of 32 bit integers. This array has more than enough bits to represent every possible internal state of the RNG (2624 * 32 > 219937-1).

    The tuple returned by get_state can be used much like a seed in order to create reproducible sequences of random numbers. For example:

    import numpy as np
    
    # randomly initialize the RNG from some platform-dependent source of entropy
    np.random.seed(None)
    
    # get the initial state of the RNG
    st0 = np.random.get_state()
    
    # draw some random numbers
    print(np.random.randint(0, 100, 10))
    # [ 8 76 76 33 77 26  3  1 68 21]
    
    # set the state back to what it was originally
    np.random.set_state(st0)
    
    # draw again
    print(np.random.randint(0, 100, 10))
    # [ 8 76 76 33 77 26  3  1 68 21]