#50825 [Bgs]: rand () and mt_rand () do not properly calculate when min=0
| From: | pajoye@php.net | Date: | Fri, 22 Jan 2010 17:59:52 +0000 |
| Subject: | #50825 [Bgs]: rand () and mt_rand () do not properly calculate when min=0 | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-146880@lists.php.net to get a copy of this message | ||
ID: 50825
Updated by: pajoye@php.net
Reported By: xeriar at gmail dot com
Status: Bogus
Bug Type: Math related
Operating System: Debian Squeeze
PHP Version: 5.2.12
New Comment:
/dev/urandom is indeed better that MT or the rather basic rand.
Previous Comments:
------------------------------------------------------------------------
[2010-01-22 17:23:08] xeriar at gmail dot com
As I mentioned, simply passing mt_rand (1,2) nets the 50/50 results
desired. Which you would have noted if you had bothered reading the
description.
It is in fact fixable, and I've created my own implementation piping
from /dev/urandom to cope with this since I obviously can't trust the
php code to.
------------------------------------------------------------------------
[2010-01-22 16:47:53] pajoye@php.net
As both implemenations are not ideal, this specific is not fixable and
won't be.
Btw, if you use better random sources, getting a 50/50 as you expect is
very unlikely .)
------------------------------------------------------------------------
[2010-01-22 16:42:56] xeriar at gmail dot com
Description:
------------
Whenever rand () or mt_rand () are passed with a min=0, 0 gets reported
less often than it should be. mt_rand (0,1) returns 1 75% of the time,
for example, while mt_rand (1,2) works as expected.
Reproduce code:
---------------
<?php
$arr = array ();
for ($i = 0; $i < 100000; $i++)
{
$c = mt_rand (0,1);
if (!isset ($arr[$c])) $arr[$c] = 1;
else $arr[$c]++;
}
ksort ($arr);
foreach ($arr as $key => $value)
echo '<b>'.$key.':</b> '.$value.'<br />';
Expected result:
----------------
0 and 1 should each get ~50,000 results
Actual result:
--------------
0 gets ~25k results and 1 gets ~75k
------------------------------------------------------------------------
--
Edit this bug report at http://bugs.php.net/?id=50825&edit=1