note 90233 added to function.rand
| From: | php at ourdetour dot com | Date: | Sat, 11 Apr 2009 14:16:00 +0000 |
| Subject: | note 90233 added to function.rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-153080@lists.php.net to get a copy of this message | ||
rand(1,2) returns 1 about 25% of the time, and 2 75% of the time.
If you want to use rand to choose evenly among a small range of numbers, you should be aware of
uneven distribution in low ranges such as rand(1,2) and rand(1,4). Here's what I found, your
mileage may vary, but please test before you assume you'll get a 50/50 distribution from
rand(1,2)
TEST CODE:
$counts = array(1=>0,0,0,0,0,0,0,0,0);
for($i=0; $i < 10000000; $i++)
{
$n = rand(1,4);
$counts[$n]++;
}
echo "Counts: ".print_r($counts,true);
RESULTS:
rand(1,2) consistently returns a 25%/75% split
[1] => 2502675
[2] => 7497325
rand(1,4) consistently returns a 6%, 31%, 31%, 31% split
[1] => 625149
[2] => 3123425
[3] => 3127953
[4] => 3123473
It appears that rand chooses your "min" boundary less frequently than the rest of your
range. If you test rand(1,9) you get similar results: the 1 will be chosen 123k times, and 2-8 will
be chosen 1.233M times each. Of course, rand(1,2) is distributed the same as rand(8,9): the
starting value always seems to be chosen less frequently.
I tested and got the same distribution from mt_rand()
----
Server IP: 209.41.74.194
Probable Submitter: 206.71.67.6
----
Manual Page -- http://www.php.net/manual/en/function.rand.php
Edit -- https://master.php.net/note/edit/90233
Del: integrated -- https://master.php.net/note/delete/90233/integrated
Del: useless -- https://master.php.net/note/delete/90233/useless
Del: bad code -- https://master.php.net/note/delete/90233/bad+code
Del: spam -- https://master.php.net/note/delete/90233/spam
Del: non-english -- https://master.php.net/note/delete/90233/non-english
Del: in docs -- https://master.php.net/note/delete/90233/in+docs
Del: other reasons-- https://master.php.net/note/delete/90233
Reject -- https://master.php.net/note/reject/90233
Search -- https://master.php.net/manage/user-notes.php