# 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*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 213, the first 14 random numbers are:
0.17, 0.56, 0, 0.46, 0.94, 0.45, 0.98, 0.53, 0.1, 0.69, 0.3, 0.93, 0.58, 0.25

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: 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

• November 7, 2005 - Added solution 1.
© 2004-19 robson | cc unless stated