Bug #60420 [NEW]: rand(0,limit) fail to hit the 0 often
From:
Operating system: Linux
PHP version: Irrelevant
Package: *General Issues
Bug Type: Bug
Bug description:rand(0,limit) fail to hit the 0 often
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 bug report at https://bugs.php.net/bug.php?id=60420&edit=1
--
Try a snapshot (PHP 5.4): https://bugs.php.net/fix.php?id=60420&r=trysnapshot54
Try a snapshot (PHP 5.3): https://bugs.php.net/fix.php?id=60420&r=trysnapshot53
Try a snapshot (trunk): https://bugs.php.net/fix.php?id=60420&r=trysnapshottrunk
Fixed in SVN: https://bugs.php.net/fix.php?id=60420&r=fixed
Fixed in SVN and need be documented: https://bugs.php.net/fix.php?id=60420&r=needdocs
Fixed in release: https://bugs.php.net/fix.php?id=60420&r=alreadyfixed
Need backtrace: https://bugs.php.net/fix.php?id=60420&r=needtrace
Need Reproduce Script: https://bugs.php.net/fix.php?id=60420&r=needscript
Try newer version: https://bugs.php.net/fix.php?id=60420&r=oldversion
Not developer issue: https://bugs.php.net/fix.php?id=60420&r=support
Expected behavior: https://bugs.php.net/fix.php?id=60420&r=notwrong
Not enough info: https://bugs.php.net/fix.php?id=60420&r=notenoughinfo
Submitted twice: https://bugs.php.net/fix.php?id=60420&r=submittedtwice
register_globals: https://bugs.php.net/fix.php?id=60420&r=globals
PHP 4 support discontinued: https://bugs.php.net/fix.php?id=60420&r=php4
Daylight Savings: https://bugs.php.net/fix.php?id=60420&r=dst
IIS Stability: https://bugs.php.net/fix.php?id=60420&r=isapi
Install GNU Sed: https://bugs.php.net/fix.php?id=60420&r=gnused
Floating point limitations: https://bugs.php.net/fix.php?id=60420&r=float
No Zend Extensions: https://bugs.php.net/fix.php?id=60420&r=nozend
MySQL Configuration Error: https://bugs.php.net/fix.php?id=60420&r=mysqlcfg
Thread (1 message)
- shai at inetb dot com