note 63828 deleted from function.mt-rand by bjori
| From: | bjori@php.net | Date: | Sun, 16 Apr 2006 12:43:49 +0000 |
| Subject: | note 63828 deleted from function.mt-rand by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-108272@lists.php.net to get a copy of this message | ||
Note Submitter: gerry-01 at 4warding dot com
----
Gerry (or "Garry" ;>) here again .
I was concerned about the implications of barnettjw's findings, so I emailed him to see if I
could get the code. It would appear that the reason he got the results he did, was because his code
was imploding his array of 50,000 numbers without specifying a glue (easy mistake to make). Because
of this the glue was defaulting to '' and just making one long number. Then when he looked
for occurrences of 1, the numbers 12-19 were also counted and the number 11 twice. The same happened
with the number 2, but less so because the string only contained numbers 20-25. To confirm this you
can add up all the occurrences in his first example and you will see that they add up to 109,843
instead of 50,000.
I have made modifications to my previous example, to take into consideration barnettjw's
alterations. For me, in the results of the following example, all numbers have an approximately
equal number of occurrences:
<?php
$iterations = 100000;
$min = 0;
$max = 50;
$testVals = array_fill($min, $max+1, 0);
$zeroPadStr = '%0'. strlen($iterations) .'d';
$zeroPadStr2 = '%0'. strlen($max) .'d';
echo 'Results from '. $iterations .' "mt_rand(0, 2)"
executions...'."<br>\n<br>\n";
for($i=0; $i<$iterations; $i++){
$randNum = mt_rand($min, $max);
$testVals[$randNum]++;
}
foreach($testVals As $testVal => $occurnaces){
$percent = $occurnaces / $iterations * 100;
$paddedTestVal = sprintf($zeroPadStr2, $testVal);
echo "<br>\n $paddedTestVal occurred $occurnaces times ($percent%)";
}
?>
As well as sending me his code, barnettjw also passed along a link to http://www.random.org/ , which is a for anybody who doesn't
want random numbers to be generated by a computer, but instead by physical elements in our
environment. I'm sure there are people who can make use of this interesting service, perhaps to
please a particularly fussy client. :D