Gergely Bertalan
Gergely Bertalan

Reputation: 53

The mt_rand() function of PHP returns only 2^31 different random numbers. How does it modify the normal Mersenne twister?

I implemented Mersenne twister in java, and it can generate 32 bit uniformly distributed random numbers in the closed interval [Integer.MIN_VALUE,Integer.MAX_VALUE].

When I call mt_rand() in PHP, it can generate 32 bit uniformly distributed random numbers in this closed interval: [0, Integer.MAX_VALUE]. This interval is just the half! It's still uniformly distributed, so it is good for generating random numbers. But if I use the same seed for my implementation and for mt_rand(), I will get different results.


Example one:

mt_srand:=1000

mt_rand()

myseed:=1000

myrand()

mt_rand returns: 753084335

myrand() returns: -1712525729


Example two:(with different seed)

mt_srand:=10000

mt_rand()

myseed:=10000

myrand()

mt_rand returns: 983171632

myrand() returns: 418336623


What should I do to get the same values if I use the same seed?

Upvotes: 0

Views: 261

Answers (1)

Klas Lindbäck
Klas Lindbäck

Reputation: 33273

What makes you think it is possible to get the same random number sequence?

To get the same sequence you need to use an identical generator algorithm, down to every last detail. One of those details is the range of the output.

The easiest way to get identical output is to change your implementation to simply call mt_rand.

Another way is to compare your source code with the source code of the mt_rand used by PHP and verify that they don't differ.

Upvotes: 0

Related Questions