JavaScript Tip: 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.

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):

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:

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:

Leave a Reply

Your email address will not be published. Required fields are marked *