note 73730 added to function.rand
| From: | phpdev at dunnbypaul dot net | Date: | Thu, 08 Mar 2007 04:51:28 +0000 |
| Subject: | note 73730 added to function.rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-124223@lists.php.net to get a copy of this message | ||
Here's an interesting note about the inferiority of the rand() function. Try, for example, the
following code...
<?php
$r = array(0,0,0,0,0,0,0,0,0,0,0);
for ($i=0;$i<1000000;$i++) {
$n = rand(0,100000);
if ($n<=10) {
$r[$n]++;
}
}
print_r($r);
?>
which produces something similar to the following output (on my windows box, where RAND_MAX is
32768):
Array
(
[0] => 31
[1] => 0
[2] => 0
[3] => 31
[4] => 0
[5] => 0
[6] => 30
[7] => 0
[8] => 0
[9] => 31
[10] => 0
)
Within this range only multiples of 3 are being selected. Also note that values that are filled are
always 30 or 31 (no other values! really!)
Now replace rand() with mt_rand() and see the difference...
Array
(
[0] => 8
[1] => 8
[2] => 14
[3] => 16
[4] => 9
[5] => 11
[6] => 8
[7] => 9
[8] => 7
[9] => 7
[10] => 9
)
Much more randomly distributed!
Conclusion: mt_rand() is not just faster, it is a far superior algorithm.
----
Server IP: 66.207.199.35
Probable Submitter: 198.53.229.242
----
Manual Page -- http://www.php.net/manual/en/function.rand.php
Edit -- https://master.php.net/note/edit/73730
Del: integrated -- https://master.php.net/note/delete/73730/integrated
Del: useless -- https://master.php.net/note/delete/73730/useless
Del: bad code -- https://master.php.net/note/delete/73730/bad+code
Del: spam -- https://master.php.net/note/delete/73730/spam
Del: non-english -- https://master.php.net/note/delete/73730/non-english
Del: in docs -- https://master.php.net/note/delete/73730/in+docs
Del: other reasons-- https://master.php.net/note/delete/73730
Reject -- https://master.php.net/note/reject/73730
Search -- https://master.php.net/manage/user-notes.php