Jump to content

"random" number generator is not random?

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1
schwza

schwza

    Newbie

  • Members
  • Pip
  • 1 posts
Here is a very simple program that tests the rand function. It computes two random numbers that are 0 or 1, and counts the number of time that they are the same. I have run this program 10+ times and the number of duplicates is always slightly over 50%. Any suggestions?

<html>
<head></head>
<?php
set_time_limit (100000);
$m = 1;
$total = 2000000;
for ($i = 1; $i < $total; $i++) {
$c1 = rand(0,$m);
$c2 = rand(0,$m);
if ($c1 == $c2)
{
$dupe++;
}
echo "dupe is $dupe";
?>
</body>
</html>

#2
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,124 posts
Although "2/1" should equal 50% it does not in the computer world. There are many issues with pseudorandom number generation but there are a few strongpoints PHP can provide.

<?php

//Set random seed
srand(microtime(true));

$min = 1;
$max = 2000000;
$count = 0;

for($i=1; $i <= $max; $i++) {
    $c1 = mt_rand(0, $min);
    $c2 = mt_rand(0, $min);
    //Properly catch count of 1.
    if ($c1 == 1) {
       $count++;
    }
}

//Print result as a float (6 digit precision)
printf("Skew is %f percent.", ($count/$max)*100);

?>
An example output is:
Skew is 49.988850 percent. 
mt_rand uses Mersenne primes (Mersenne twister) and srand seeds the pseudorandom generator. They are indisposable tools to attempt better randomness!

Edited by Alexander, 04 June 2010 - 02:20 AM.
rehauling