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>
"random" number generator is not random?
Started by schwza, Jun 03 2010 09:53 PM
1 reply to this topic
#1
Posted 03 June 2010 - 09:53 PM
|
|
|
#2
Posted 04 June 2010 - 12:58 AM
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


Sign In
Create Account

Back to top









