My First JavaScript Problems: Generating Random Whole Numbers

| Comments

Anyone who considers arithmetical methods of producing random digits is, of course, in a state of sin.

John von Neumann

This is a post about understanding the code we use. I’m taking a look at the JavaScript code we need to generate any random whole number between 1 and X:

1
Math.floor(Math.random() * X + 1)

The problem: I spotted and understood the two simple arithmetic operators (* for multiplication, and + for addition), but I wasn’t sure about much else. I particularly wondered how the +1 fits into the equation. Talk about random stuff!

The Math object: JavaScript supports a number of built-in (already defined, so we don’t have to define them) functions. Mathematical functions are all stored as properties of a single Math object; they are methods of the Math object. We use dot notation to refer to any property of an object, e.g.:

1
Math.random()

Math.random() returns a pseudorandom number between 0.0 (inclusive) and 1.0 (exclusive), e.g.:

0.7452051765285432

What the decimal!?: Long random sequences require a lot of memory, so computers instead produce random-looking sequences. A computer takes the input for the next calculation from its last output. The entire sequence is predetermined by the initial input it’s seeded with, and is destined to repeat when an already used input crops up again.

JavaScript’s random number generator takes its initial input from the current time in milliseconds (source: Mozilla’s implementation of the JavaScript engine); this is the only random element.

With a two-digit input, a computer can produce a maximum of 100 digits before reusing the input and repeating the sequence. I expect this is why Math.random() deals in values with lots of digits; it’s for our own programme’s better security.

Multiply by X: To get values between 0 and 10 (but never 10 precisely), we multiply Math.random() by our maximum value (10). This produces values that look like this:

7.4520517652854320

The next method of the Math object on our list - Math.floor() - rounds a value down to the closest integer, e.g.:

1
2
3
4
5
Math.floor(7.4520517652854320);    //  Result is 7.0

Math.floor(0.7130960305221379);    //  Result is 0.0

Math.floor(9.9244563927873970);    //  Result is 9.0

This gives us a value between 0 and 9. Suddenly, the +1 makes sense! Here’s the code for generating any random whole number between 1 and 10:

1
Math.floor(Math.random() * 10 + 1)

14 Aug. 2012: Post updated in response to insight from RobIII.

Comments