Ángel Ortega III

Un naufragio personal

A simple pseudorandom number generator

Recently, a member of a game development mailing list asked me what random number algorithm I used in the Space Plumber game. This small document describes it.

First, I want to remember everyone that real random numbers are impossible to create on a computer because computing is deterministic BLAH BLAH BLAH I JUST WANT THE FUCKING CODE.

Ok, here it is:

 unsigned int sp_random(unsigned int *seed, unsigned int range)
 /* Space Plumber's random */
 {
     *seed = (*seed * 58321) + 11113;
     return (*seed >> 16) % range;
 }

It accepts two arguments:

seed
a pointer to an integer containing the random seed. If you only need one, you can use a global value. As a start fill it with the output of time() or something like that.
range
The maximum value to return, plus 1. The maximum range is 65535.

The sp_ in the name, unsurprisingly, comes from Space Plumber. It's not written exactly this way there, though.

The output value will be an integer from 0 to range-1, sufficiently unexpected to be used as a random number in games and such (don't make me laugh about cryptographically-secure values).

It's based on the wrapping of the 32 bit multiplying operation, so it won't work with floating point arithmetic.

documents, programming, algorithms, space plumber