triptico.com

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.

Visitor comments

Spider
2011-01-14
But where do magic numbers 58231 and 11113 come from?

Angel Ortega
2011-01-14
I don't remember exactly where I took them from (probably my ass), but I think any other pair of prime numbers will work.

Spider
2011-01-14
Is it possible that they were choosen when Space Plumber was a 16 bit application?

Angel Ortega
2011-01-14
I don't know where you've taken that idea, Space Plumber was never a 16 bit application. I started to work on it under SunOS and DJGPP with a funny thing called a "DOS Extender", so it has been 32 bits from the beginning.

Yes, probably those systems are older than you.

Min
2011-01-26
May I reuse it?

Angel Ortega
2011-01-26
@Min: of course. Happy hacking. Tell me about it when it's done.

Min
2011-01-26
It will be used in an iPhone App. I still have to test it, though.

Min
2011-01-26
I mean if your function meets my needs.

mati
2014-03-05
2 questions: 1. how can a RNG can be verified? example: average values should always be maxvalue/2, same quantity of even/uneven numbers.. etc? more ideas? how can i test repetitive sequences of numbers? 2. analogously, would a 32bit random gen work? ...(*seed >> 32) % range

Ángel Ortega
2014-03-06
There are some official ways to test for a valid RNG (cryptographically speaking) but you only need to run some statistic tests to count the number of contiguous sets of 0 and 1, then of 00, 01, 10 and 11, and so on. If they are evenly spread, the RNG is valid.