Random Number Generator

Generate a random number between
and

Information for Programmers

JavaScript code for generating a random number

Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;

Math.floor() vs Math.round()

Why use Math.floor() and not Math.round()? As an example, let's say that you want to generate numbers in the range of 0 to 2. If you do Math.round(0.4) you get 0, and if you do Math.round(0.5) you get 1. On the other end of your random range, if you do Math.round(1.4) you get 1, and if you do Math.round(1.5) you get 2.

But this means that you are half as likely of getting 0 and 2 as you are of getting 1. Look at this number line:


|        0         |                  1                    |          2           |
0.0-0.1-0.2-0.3-0.4-0.5-0.6-0.7-0.8-0.9-1.0-1.1-1.2-1.3-1.4-1.5-1.6-1.7-1.8-1.9-2.0

Notice that the space for 0 and 2 is smaller than the space for 1. If you wanted to have an equal chance of getting 0, 1, and 2 using Math.round(), you would have do some manipulation with decimal numbers in your random number formula. However, there is an easier way.

If you use Math.floor() on numbers like 0.4, 1.4, and 2.4 for example, this is the number line that you get:


|                  0                   |                   1                   |                   2                  |
0.0-0.1-0.2-0.3-0.4-0.5-0.6-0.7-0.8-0.9-1.0-1.1-1.2-1.3-1.4-1.5-1.6-1.7-1.8-1.9-2.0-2.1-2.2-2.3-2.4-2.5-2.6-2.7-2.8-2.9

As you can see, each of the three numbers in the 0 to 2 range has the same amount of space on this number line, making each one equally likely when you put a random number into Math.floor().