note 61950 added to function.mt-rand
| From: | Gerry at osu1 dot php dot net | Date: | Wed, 15 Feb 2006 20:35:41 +0000 |
| Subject: | note 61950 added to function.mt-rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-103794@lists.php.net to get a copy of this message | ||
Quote from the documentation:
"If you want a random number between 5 and 15 (inclusive), for example, use mt_rand (5,
15)."
Just so that it is clear exactly what this means (because it wasn't for me, or maybe I'm
just pedantic ;) ). The number will be "inclusive" of both the 5 and the 15 and all
numbers should have an approximately equal number of occurrences.
I.E. Running mt_rand(0, 2) 100000 times produced the following for me:
Zero occurred 33639 times
One occurred 33132 times
Two occurred 33229 times
Other runs also produced nearly equal results.
The code used for the tests:
<?php
$zero = $one = $two = $other = 0;
$iterations = 100000;
$zeroPadStr = '%0'. strlen($iterations) .'d';
echo 'Results from '. $iterations .' "mt_rand(0, 2)"
executions...'."<br>\n<br>\n";
for($i=0; $i<$iterations; $i++){
$randNum = mt_rand(0, 2);
echo 'Test #'. sprintf($zeroPadStr, $i+1)
.': '. $randNum ."<br>\n";
switch ($randNum){
case 0: $zero++; break;
case 1: $one++; break;
case 2: $two++; break;
default: $other++;
}
}
echo "<br>\nZero occurred ". $zero .' times';
echo "<br>\nOne occurred ". $one .' times';
echo "<br>\nTwo occurred ". $two .' times';
if($other)
echo "<br>\nNumber of other values = ". $other;
?>
----
Server IP: 203.16.234.19
Probable Submitter: 202.89.174.242
----
Manual Page -- http://www.php.net/manual/en/function.mt-rand.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+61950
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+61950&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+61950&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+61950&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+61950&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+61950&report=yes&reason=non-english
Delete: already in docs -- http://master.php.net/manage/user-notes.php?action=delete+61950&report=yes&reason=already+in+docs
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+61950&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+61950&report=yes
Search -- http://master.php.net/manage/user-notes.php