How to test the distribution of your random number generator function. Example provided in PHP.

<?php
// Total number of iterations to calculate distribution
$ITERATIONS = 100;
// Upper range of random numbers
$NUM = 10;
// Iterate!
$sum = 0;
foreach (range(0,$ITERATIONS) as $i) {
$sum += rand(0,$NUM);
}
// Echo the average of all the random numbers
echo ($sum / $ITERATIONS) . "\n";
?>

### Like this:

Like Loading...

*Related*

LOL. That’s not how you test a distribution of random numbers. See the Diehard test suite, which merely qualifies as a good starting point.

Also, PHP’s rand() function is a rather weak PRNG with a small period. mt_rand() is better but still a PRNG. Never use a PRNG where application security is involved. For that, you need a CSPRNG.

Ha ha, thanks for sharing. I should have clarified that this is not meant to test for security… it’s just a quick script I put together to see the average of random numbers generated over an iteration to see if it gets to the mean. I did find that for larger samples/iterations, the average does seem to get closer to the exact mean.

I think the conclusions drawn from this would be a little bit unfair given that the bound is considerably small. In addition it has not been seeded, does there exist a considerable difference when given a seed?

I definitely agree. I haven’t tested it with a seed yet.