Jan 7 2006

Random Stuff. Seriously.

Recently I went looking for a simple and easy to understand source of pseudo-random numbers. Amazingly it’s surprisingly difficult to find information on anything not requiring PhD level mathematics. So here’s one anybody can understand:


int random;

void update() {
random = ( random + STEP ) % MAX;
}

As you can see, the algorithm works by adding STEP to the previous value, and storing the remainder of the division between it and MAX as the next value. As a result the value of random will always be between 0 and MAX-1 inclusive.

Only certain combinations of STEP and MAX will give random-like sequences. If STEP is zero, the value of random obviously never changes. If STEP is small with respect to MAX, the value of random counts up uniformly up to MAX, before wrapping around from a low value.

The sequence is periodic, when the sequence returns to the initial value of random it will repeat. When random does return to it’s initial value, the accumulated step has reached a value than divides MAX with a remainder of zero. The period of the sequence is therefore given by the lowest common multiple of STEP and MAX, divided by STEP.

If both STEP and MAX are prime numbers, then the lowest common multiple is easily given by STEP*MAX, and therefore the period is equal to MAX.

Anyway, with a bit of experimentation, this one-liner gives an acceptable way of getting reasonably unpredictable sequences of numbers.

Cheers!
Martin