MTRandom: An Objective-C Random Number Generator

September 3, 2012

Most of the time when we need a random number, we use srandom() & random(), or perhaps arc4random(). In the old days we might have used srand() and rand(), until somebody told us that random() was better.

Sometimes we want a sequence of random numbers to be reproducible. Say we’re writing our own Minecraft and we want users to be able to share seeds for the landscapes they find. The above functions work fine for that, as long as we’re the only one using them. Unfortunately they’re not thread safe (see my test code to confirm). They manage a single state behind the scenes, so if we wanted to run, say, two landscape generation routines in parallel, we’d be out of luck.

That’s where MTRandom comes in. MTRandom is an Objective-C wrapper for Mersenne Twister, a pseudo-random number generator.

MTRandom *random = [[MTRandom alloc] initWithSeed:5];
uint32_t r = [random randomUInt32From:5 to:10];   // [5, 10]
double   s = [random randomDouble];               // [0.0, 1.0]
double   u = [random randomDoubleFrom:0 to:M_PI]; // [0, 3.14159...]

There are a few more examples in the README.markdown.

It also conforms to NSCoding and NSCopying, so you can archive it with game state, or make copies when searching a game tree. The repository includes a set of basic unit tests, and best of all it’s BSD licensed (even Mersenne Twister). It’s available on GitHub: