Monthly Archives: January 2015

Random numbers

Back in the before time, in the long long ago, all good coders knew that rand() was a dodgy pile of crap.

The pseudo-random numbers it generated were more random in the higher order bits than in the lower order bits, which meant that using a modulus to create a random value left you with weak random numbers.

Using mod is the really easy way to get a random value. You want a number from 0 to999, sure, just do


it’s easy. Nowadays that kind of code is fine, as rand() has been fixed just about everywhere that it matters. However, the manual page for rand still thinks there’s a problem, and suggests the following:

"If you want to generate a random integer between 1 and 10, you
should always do it by using high-order bits, as in

j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));

This is a pretty terrible idea, and it causes all kinds of problems when porting to Linux.

On Windows, this code works, and that’s great for Windows. On Linux, it breaks horribly. This is because on most flavours of Linux, RAND_MAX is the same value as MAX_INT, which means adding one to it will always flip your random number to a negative value.

It works on Windows, because RAND_MAX is a smaller number, in most cases 32768, which is way below MAX_INT of 2147483647

If you keep finding your random numbers are going negative when you’re doing what the manual tells you to do, change it from this old style, and just use the modulus method. These days, it’s perfectly safe.