Random number from 1 to 100

Why is one added to the result in this code?

console.log(Math.floor(Math.random() * 100) + 1);

Will this code output a number from 1 to 100 inclusive, or from 2 to 99?

Author: Igor, 2018-08-02

2 answers

The Math.random() method returns a pseudo-random floating-point number from the range [0, 1), that is, from 0 (inclusive) to 1 (but not including 1), which can then be scaled to the desired range.

Therefore, when multiplying by 100, we get the range от 0 до 99, and when incrementing this range by 1, we get от 1 до 100.

If you want to get the range от 2 до 99, then you need the following coefficients:

Math.floor(Math.random() * 98) + 2

If you want to get the range от 0 до 100, then you need the following coefficient:

Math.floor(Math.random() * 101)

There is another important point here - what method do you use for rounding: Math.floor, Math.round or Math.ceil.

In the case of Math.floor- rounding down. Rounds the argument to the nearest smaller integer.

Math.floor(1.9) = 1

In the case of Math.round, it returns the nearest integer.

Math.round(1.5) = 2
Math.round(1.4) = 1

In the case of Math.ceil - rounding up. Rounds the argument to the nearest larger integer.

Math.ceil(1.1) = 2

Therefore:

Math.floor(Math.random()*100) - диапазон от 0 до 99
Math.round(Math.random()*100) - диапазон от 0 до 100
Math.ceil(Math.random()*100) - диапазон от 1 до 100

To summarize: it is better to use Math.floor or Math.ceil as rounding methods, since in the case of Math.round we get an uneven probability of falling out for the lower and upper bounds on 0.4(9) versus 0.(9) for all other integers in the range.

Example: from 0 to 0.4(9) is rounded to 0, from 99.5 to 99.(9) is rounded to 100, against say from 2.5 to 3.4(9), which is rounded to 2.

References: 1, 2, 3.

 9
Author: Элчин Хасиев, 2018-08-12 10:11:35

Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

... returns a floating-point, pseudo-random number in the range 0–1 (inclusive of 0, but not 1)

... returns a pseudo-random floating-point number in the range 0-1 (including zero, but not including one)

 1
Author: Igor, 2018-08-02 13:55:18