php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #60420 rand(0,limit) fail to hit the 0 often
Submitted: 2011-11-30 18:47 UTC Modified: 2011-12-07 05:30 UTC
Votes:3
Avg. Score:1.0 ± 0.0
Reproduced:0 of 3 (0.0%)
From: shai at inetb dot com Assigned: frozenfire (profile)
Status: Closed Package: Documentation problem
PHP Version: Irrelevant OS: Linux
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: shai at inetb dot com
New email:
PHP Version: OS:

 

 [2011-11-30 18:47 UTC] 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 


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2011-12-07 05:25 UTC] yohgaki@php.net
-Type: Bug +Type: Documentation Problem -Package: *General Issues +Package: Documentation problem
 [2011-12-07 05:25 UTC] yohgaki@php.net
mt_rand has better algorithm. Documentation should encourage use of mt_rand 
instead of rand.
 [2011-12-07 05:30 UTC] frozenfire@php.net
Documentation does suggest use of mt_rand in see-also.
 [2011-12-07 05:30 UTC] frozenfire@php.net
-Status: Open +Status: Closed -Assigned To: +Assigned To: frozenfire
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Sat Aug 16 02:00:03 2025 UTC