Internal state of a random python module

import random
random.seed(234)
state = random.getstate()

      

The result state is a tuple:

(3, (.... many long integers...),  None)

      

What does this mean? I know I can save state and use random.setstate (state) to restore internal state for whatever random number generator used in this module. But I do not know what these values ​​mean in the state. There are no details in the official document. I am guessing it might mean parameters to define a random state.

+3


source to share


1 answer


The algorithm used since Python 2.3 is the Mersenne Twister . The docs note that state is implementation specific. So I wouldn't rely on any specific state details unless you really need to.

Mersenne Twister starts by initializing an array of integers using seed. Here's a helpful (lightly edited) snippet of Python code from the Wikipedia article on Mersenne Twister:

    state = [0] * 624
    state[0] = seed
    for i in range(1, 624):
        state[i] = int(
            0xFFFFFFFF & (1812433253 * (state[i - 1] ^ state[i - 1] >> 30) + i)
        )

      



Note that this is unsigned arithmetic. This is the algorithm used to generate state, as seen in the CPython source code .

CPython's code sets 624 as the last element of the state to use as an index variable, so the state array actually has 625 elements, compared to 624 in the Wikipedia snippet above. The pivot operation uses this index variable.

When I compared the results of using Wikipedia's Python code with a random module, I didn't get the same integers 624. I think this is probably a combination of Python code that doesn't do the same arithmetic as C code, and the seed is driven by C code. I'll see when I have more time, I hope.

+1


source







All Articles