Testing Distribution of Random Number Generation in PHP

26 Jun

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";
?>
Advertisements

4 Responses to “Testing Distribution of Random Number Generation in PHP”

  1. John Herman June 27, 2012 at 11:31 am #

    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.

    • sumanrs July 5, 2012 at 12:27 pm #

      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.

  2. John Doe October 23, 2012 at 5:26 am #

    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?

    • sumanrs November 13, 2012 at 5:03 pm #

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: