Implementing a Clock Drift random number generator in PHP
Posted
by Excl
on Stack Overflow
See other posts from Stack Overflow
or by Excl
Published on 2010-06-05T13:38:35Z
Indexed on
2010/06/05
13:42 UTC
Read the original article
Hit count: 184
Hi, I wrote the following code:
function create_rand($time) {
$counter = 0;
$stop = microtime(true) + $time;
while(microtime(true) < $stop)
$counter++;
return $counter;
}
function create_rand_max($time, $a, $b = false) {
$rand_a = create_rand($time);
$rand_b = create_rand($time);
$rand_c = create_rand($time);
$max = max($rand_a, $rand_b, $rand_c);
$min = min($rand_a, $rand_b, $rand_c);
if($max === $min)
return create_rand_max($time, $a, $b);
$middle = $rand_a + $rand_b + $rand_c - $max - $min;
if($b !== false)
return min($a, $b) + ($middle - $min) * (max($a, $b) - min($a, $b)) / ($max - $min);
return ($middle - $min) * $a / ($max - $min);
}
$stop = 1000;
$sum = 0;
for($i = 0; $i < $stop; $i++) {
$sum += create_rand_max(0.001, 100, 200);
}
echo $sum / $stop;
The average is usually between 157 to 161, instead of ~150.
Any ideas?
© Stack Overflow or respective owner