Doc #60420 [Opn->Csd]: rand(0,limit) fail to hit the 0 often

From: Date: Wed, 07 Dec 2011 05:30:55 +0000
Subject: Doc #60420 [Opn->Csd]: rand(0,limit) fail to hit the 0 often
References: 1  Groups: php.doc.bugs 
Request: Send a blank email to doc-bugs+get-7612@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=60420&edit=1 ID: 60420 Updated by: frozenfire@php.net Reported by: shai at inetb dot com Summary: rand(0,limit) fail to hit the 0 often -Status: Open +Status: Closed Type: Documentation Problem Package: Documentation problem Operating System: Linux PHP Version: Irrelevant -Assigned To: +Assigned To: frozenfire Block user comment: N Private report: N New Comment: Documentation does suggest use of mt_rand in see-also. Previous Comments: ------------------------------------------------------------------------ [2011-12-07 05:25:01] yohgaki@php.net mt_rand has better algorithm. Documentation should encourage use of mt_rand instead of rand. ------------------------------------------------------------------------ [2011-11-30 18:47:38] shai at inetb dot com Description: ------------ I notices that something in my code not giving expected result and when digging some more I notices that rand(0,limit) don't give the same "opportunity" to that '0'. in other words, the random distribution is very bad. in a 10,000 calls to random like this: rand(0,7), I noticed that the 0 hit only 2000 while 1,2,3,4,5,6,7 all hit about 16300 times. this is a ratio of 770% If the range start with number bigger than 0, it works well. ex. rand(1,8)-1 work correctly but rand(0,7) doesn't --- From manual page: http://www.php.net/function.rand#refsect1-function.rand- description --- Test script: --------------- $ar =array('AA','BB','CC','DD','EE','FF','GG'); $cnt=array(); $len=count($ar)-1; for($i=0;$i<100000;$i++){ $c = $ar[rand(0,$len)]; @$cnt[$c]++; } print_r($cnt); ---- result: [BB] => 16245 [AA] => 2003 [FF] => 16260 [EE] => 16281 [DD] => 16369 [GG] => 16508 [CC] => 16334 Expected result: ---------------- the expected result of course should be that rand(0,limit) over many calls will distribute the hits evenly between all the range ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=60420&edit=1

« previous php.doc.bugs (#7612) next »