Followup: PHP: rand() vs. mt_rand()
My past comparison of rand() and mt_rand() only compared the speed, and I saw very little difference. This time I'll compare how truly random the numbers each function produces are. The code used to test this is:
<?php
$img = imagecreatetruecolor(512,512);
$i = 0;
while($i < 512*512) {
imagesetpixel(
$img,
mt_rand(0,512),
mt_rand(0,512),
imagecolorallocatealpha(
$img,
mt_rand(0,255),
mt_rand(0,255),
mt_rand(0,255),
mt_rand(0,127)
)
);
$i++;
}
imagepng($img,"mt_rand.png");
imagedestroy($img);
$img = imagecreatetruecolor(512,512);
$i = 0;
while($i < 512*512) {
imagesetpixel(
$img,
rand(0,512),
rand(0,512),
imagecolorallocatealpha(
$img,
rand(0,255),
rand(0,255),
rand(0,255),
rand(0,127)
)
);
$i++;
}
imagepng($img,"rand.png");
imagedestroy($img);
?>
On Linux (Slackware 10.2), the results looked fine, two seemingly random graphs were produced. On Windows (XP), however, the results were drastically different between functions:
rand()
mt_rand()
So, if your code relies on random numbers, and you plan on using it on multiple operating systems, mt_rand() appears to be the way to go.
Comments
I fixed the messed up bbcode in this article. Everything looks good now.
By T.J. 08/30/07 06:37:57
Nice comparison test.
Graphing out the results is a straight forward way to show the randomness of both function.
Graphing out the results is a straight forward way to show the randomness of both function.
By Google rocks 01/04/08 12:59:56
this is a great way to visualize it. I wonder if you shut down the program and restart it, if it will produce the same image.
Some random functions in other languages have this problem. They may produce seemingly very random numbers, but will produce the SAME sequence of "random" numbers each time the program is run.
Some random functions in other languages have this problem. They may produce seemingly very random numbers, but will produce the SAME sequence of "random" numbers each time the program is run.
By MG 01/30/09 03:00:52
