note 90233 deleted from function.rand by danbrown

From: Date: Sat, 11 Apr 2009 15:02:28 +0000
Subject: note 90233 deleted from function.rand by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-153081@lists.php.net to get a copy of this message
Note Submitter: php at ourdetour dot com ---- 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()

« previous php.notes (#153081) next »