November 1, 2006

Is Random Really Random?

As random as random can be.

A computer cannot generate a truly random number because computation is deterministic: it follows an unbroken chain of cause and effect in which no truly random events ever occur. Instead, it uses a set of complex algorithms to generate what's known as a pseudorandom number --- a number that gives the appearance of randomness, and is good enough for any practical purpose.

Math.random(); // number between 0 and 1

This produces a number between zero and one (excluding either limit).

If we multiply that by ten and use Math.floor to round down, we'll end up with an integer between zero and nine (inclusive):

Math.floor(Math.random() * 10); // integer 0 to 9

So the number by which we multiply the output of Math.random determines the upper limit. If we want an integer between zero and n (inclusive), we then multiply by n + 1.

If we add five to our sample result, we'll get a number between five and 14:

5 + Math.floor(Math.random() * 10); // integer 5 to 14

This defines the lower limit, and shifts the range to the final upper limit.

We convert this equation to a function that receives the lower (min) and upper limit (max) we're shooting for. Both limits are used to calculate the number by which we multiply the output of Math.random:

min + Math.floor(Math.random() * (max - min + 1));

I put this all together and I created a simple example and here is the code (.zip) as well.