[Numpy-discussion] Mersenne Twister: Python vs. NumPy

Robert Kern robert.kern at gmail.com
Fri Dec 30 10:36:19 EST 2011

On Fri, Dec 30, 2011 at 15:13, Alan G Isaac <alan.isaac at gmail.com> wrote:
> If I seed NumPy's random number generator, I get the
> expected sequence.

What do you mean by "expected"? Where are these expectations coming
from? Other implementations of the Mersenne Twister?

> If I use the same seed for Python's
> random number generator, I get a different sequence.
> 1. Why does the Python sequence differ from others?

The initialization algorithm that takes the input seed (usually just
an integer) to a 624-word uint32 array that is the Mersenne Twister's
state vector. There are two initialization modes that are fairly
standard (since they were distributed with the original published MT
sources). One takes a 32-bit int, and the other takes an array of
32-bit ints.

For numpy, I made the choice that if the integer seed fits into the
uint32, then we would just use the initialization function for that.
Python just treats any integer input as if it were a Python long
object, breaks it up into 32-bit words and uses the array
initialization function.

> 2. Can I somehow put both MT's in a common state?

With a little bit of work, yes. Look at random.Random.getstate() and
np.random.RandomState.get_state() and their associated setter
functions. You really just need to reformat the information to be
acceptable to the other.

Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
  -- Umberto Eco

More information about the NumPy-Discussion mailing list