php.net |  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
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: xeriar at gmail dot com
New email:
PHP Version: OS:

 

 [2010-01-22 16:42 UTC] 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

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2010-01-22 16:47 UTC] 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 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] pajoye@php.net
/dev/urandom is indeed better that MT or the rather basic rand.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Wed Jan 15 08:01:29 2025 UTC