Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between mt_rand() and rand()

What is the difference between using mt_rand($min, $max) and rand($min, $max) about the speed?

like image 552
Thomas Rbt Avatar asked Feb 27 '15 08:02

Thomas Rbt


People also ask

Is mt_ rand random?

The mt_rand() function generates a random integer using the Mersenne Twister algorithm. Example tip: If you want a random integer between 10 and 100 (inclusive), use mt_rand (10,100).

How can create random number in PHP?

The rand() function generates a random integer. Example tip: If you want a random integer between 10 and 100 (inclusive), use rand (10,100). Tip: As of PHP 7.1, the rand() function has been an alias of the mt_rand() function.

Is Mt_rand secure?

From http://php.net/manual/en/function.mt-rand.php: Caution This function does not generate cryptographically secure values, and should not be used for cryptographic purposes.


1 Answers

Update

Since PHP 7.1 mt_rand has superseded rand completely, and rand was made an alias for mt_rand. The answer below focuses on the differences between the two functions for older versions, and the reasons for introducing mt_rand.


Speed was not why mt_rand was introduced!

The rand function existed way before mt_rand, but it was deeply flawed. A PRNG must get some entropy, a number from which it generates a sequence of random numbers. If you print out a list of ten numbers that were generated by rand() like so:

for ($i=0;$i<10;++$i)     echo rand(), PHP_EOL; 

The output can be used to work out what the rand seed was, and with it, you can predict the next random numbers. There are tools out there that do this, so google a bit and test it.

There's also an issue with rand relativily quickly showing patterns in its random numbers as demonstrated here. A problem mt_rand seems to solve a lot better, too.

mt_rand uses a better randomization algorithm (Mersenne Twist), which requires more random numbers to be known before the seed can be determined and is faster. This does not mean that mt_rand is, by definition, faster than rand is, this only means that the way the numbers are generated is faster, and appears to have no real impact on the function's performance, as other answers here have demonstrated.
Either way, have a look at the mt_srand and the srand docs. I'm sure they'll contain some more info

If mt_rand's algorithm translates in an increase in performance, then that's great for you, but it's a happy coincidence. TL;TR:

mt_rand was introduced to fix the problems that exist in rand!

like image 183
Elias Van Ootegem Avatar answered Sep 18 '22 23:09

Elias Van Ootegem