Tesla
Tesla

Reputation: 813

Does seeding mt_rand with a true random number make the result of mt_rand truely random as well?

If I have a truely random number and I use mt_srand to seed mt_rand with the truly random number before I use mt_rand, will this mean the result of mt_rand is now also truly random rather than pseudorandom?

In otherwords, would the below code produce a truly random integer between the given minimum and maximum value

function RandomInteger($min, $max)
{
    $trueRandomNumber = GetTrueRandomNumber();

    mt_srand($trueRandomNumber);
    return mt_rand($min, $max);
}

Secondly, should the true random number used to seed mt_srand be of 32 integers?

Upvotes: 1

Views: 366

Answers (2)

CubicleSoft
CubicleSoft

Reputation: 2512

Looking at your code, my guess is that you are getting some value from GetTrueRandomNumber() (code is missing) but then you want that number to be in a specific range of values. So you are taking that output and inputting it into mt_rand() because it has a method of generating a number in a specific range.

While not a direct answer to your question, a better solution is to first figure out the range of values you want (i.e. as if the input $min was 0 and $max was $max - $min). Then, figure out the maximum number of bits that are required to obtain a value in that range. Then, extract that number of bits from the output of GetTrueRandomNumber(). If the value is within the range, return the number + the original $min value. If the value isn't within the range, get more bits of data. The key is to throw away bits until you get some in the desired range.

If need example source code for this, try:

http://barebonescms.com/documentation/csprng/

You should be able to put something similar together. I'd be wary of using mt_rand() for anything like this but it might be okay in this very specific instance. It depends on what you plan on using it for. It also depends highly on how well distributed the first number from Mersenne Twister actually is. I don't think anyone's done any work on that. MT is intended to be seeded one time - who knows what the distribution pattern is for repeatedly seeding it. Also, if other code uses mt_rand(), you risk exposure of your function's state based on later values that might get generated by later mt_rand() calls.

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798676

No. Mersenne twisters are always pseudorandom. The seed only determines where in the sequence it starts.

Upvotes: 1

Related Questions