Anyone who considers arithmetical methods of producing random digits is, of course, in a state of sin.
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!
Math object; they are methods of the
Math object. We use dot notation to refer to any property of an object, e.g.:
Math.random() returns a pseudorandom number between
0.0 (inclusive) and
1.0 (exclusive), e.g.:
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.
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.
X: To get values between
10 (but never
10 precisely), we multiply
Math.random() by our maximum value (
10). This produces values that look like this:
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
This gives us a value between
9. Suddenly, the
+1 makes sense! Here’s the code for generating any random whole number between
14 Aug. 2012: Post updated in response to insight from RobIII.