|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #50825 rand () and mt_rand () do not properly calculate when min=0
Submitted: 2010-01-22 16:42 UTC Modified: 2010-01-22 17:59 UTC
From: xeriar at gmail dot com Assigned:
Status: Not a bug Package: Math related
PHP Version: 5.2.12 OS: Debian Squeeze
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
Block user comment
Status: Assign to:
Bug Type:
From: xeriar at gmail dot com
New email:
PHP Version: OS:


 [2010-01-22 16:42 UTC] xeriar at gmail dot com
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:
  $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


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2010-01-22 16:47 UTC]
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 17:23 UTC] 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 17:59 UTC]
/dev/urandom is indeed better that MT or the rather basic rand.
PHP Copyright © 2001-2022 The PHP Group
All rights reserved.
Last updated: Mon Jul 04 00:05:44 2022 UTC