Robson » Little Red Book » Random Numbers #2

Chapter 7 - Question 3

Develop a recurrence relation that can be used as the basis for a pseudo-random number-generator that, from a given initial 'seed', produces real values R: 0 <= R < 1.

Solution 1

PHP:

<?
   // random number generator
   // returns the specified amount of random numbers based on the seed
   function random_numbers($seed, $amount)
   {
       // loop for each amount
       for (; $amount > 0; $amount--)
       {
           // get the current microseconds
           $microseconds = explode(' ', microtime());
           // get the last two digits of the microseconds
           $random = substr($microseconds[0]*1, -2, 2);
           // add that to the seed
           $seed += $random;
           // mod the result by 100 to get a two digit number
           $seed %= 100;
           // add this number to the array
           $generated[] = $seed / 100;
       }
       // return all the random numbers
       return $generated;
   }
   
   // generate a random seed value
   // any number can be used to start
   $seed = mt_rand(1, 500);
   // generate a random amount of random numbers to return
   $amount = mt_rand(5, 15);
   
   // show the seed and amount
   echo 'From the seed ' . $seed . ', the first ' . $amount . ' random numbers are:<br/>';
   // show the random numbers generated
   echo implode(', ', random_numbers($seed, $amount));
?>

Which produces:

From the seed 134, the first 11 random numbers are:
0.51, 0.93, 0.39, 0.34, 0.87, 0.43, 0.02, 0.63, 0.27, 0.94, 0.91

I wanted to see how random my random number generator is. So I ran the script three times outputting 500,000 values each time and added up the frequency each number appeared. The average frequency should be around 15,000. Here's a chart showing the frequency of all the numbers:

Frequency chart

The faded-salmon line shows that all the numbers appear around the amount they are expected to appear, so my random number generator can be considered random!

Log

© 2004-17 robson | cc unless stated