note 117115 added to function.rand
| From: | Wirek | Date: | Thu, 16 Apr 2015 11:51:56 +0000 |
| Subject: | note 117115 added to function.rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-202283@lists.php.net to get a copy of this message | ||
I agree with Sebmil (http://php.net/manual/en/function.array-rand.php#105265) that
"array_rand()" produces weird and very uneven random distribution (as of my local PHP
5.3.8 and my public host's PHP 5.2.17).
Unfortunately, I haven't got any access either to a server with the latest PHP version. My info
is for those of you who like to check things for themselves and who don't believe all of the
official statements in the docs.
I've made a simple adjustment of his test code like this:
<?php
$s=1; // Start value
$c=50; // Count / End value
$test=array_fill($s, $c, 0);
$ts=microtime(true);
for($i=0; $i<5000000; $i++){
$idx=mt_rand($s, $c); // Try it with rand() - simpler but more evenly distributed than mt_rand()
$test[$idx]++;
}
$te=microtime(true);
$te=($te-$ts)*1000.0; // Loop time in miliseconds
asort($test);
echo "Test mt_rand() in ".$te." ms: <br/>\n";
foreach($test as $k=>$v) echo "$k :\t$v <br/>\n";
?>
And it appears to me that simple "$idx=rand(0, count($test)-1);" is much better than
"$idx=array_rand($test, 1);".
And what's more the simpler and a bit slower (0 ms up to total 712.357 ms at 5 mln cycles)
"rand()" is better than "mt_rand()" in simple everyday use cases because it is
more evenly distributed (difference least vs. most often numbers: ca. 0.20-1.28 % for
"rand()" vs. ca. 1.43-1.68 % for "mt_rand()").
Try it for yourself... although it depends on your software and hardware configuration, range of
numbers to choose from (due to random patterns), number of cycles in the loop, and temporary
(public) server load as well.
----
Server IP: 72.52.91.14
Probable Submitter: 78.10.57.42
----
Manual Page -- http://php.net/manual/en/function.rand.php
Edit -- https://master.php.net/note/edit/117115
Del: integrated -- https://master.php.net/note/delete/117115/integrated
Del: useless -- https://master.php.net/note/delete/117115/useless
Del: bad code -- https://master.php.net/note/delete/117115/bad+code
Del: spam -- https://master.php.net/note/delete/117115/spam
Del: non-english -- https://master.php.net/note/delete/117115/non-english
Del: in docs -- https://master.php.net/note/delete/117115/in+docs
Del: other reasons-- https://master.php.net/note/delete/117115
Reject -- https://master.php.net/note/reject/117115
Search -- https://master.php.net/manage/user-notes.php