When it comes to making random numbers in Javascript, I have always seen that they use the typical:
Math.floor(Math.random() * (max - min + 1) + min);
And from this doubts arose, why should the difference be multiplied between max y min
? , because adding 1
it makes the maximum limit inclusive ? and also why do it with Math.floor
and not just do it with toFixed(0)
, so it would be more accurate ?
Let's analyze the line:
Math.random()
returns a random value in the range [0..1), that means that if we want a random between min and max, we will have to do a series of transformations:[0..1)
has a size of 1, but we want it to be[min..max]
, which size ismax - min
, that explains the multiplication.We also want to move the range from [0..(max-min)) to [min..max), so min is added to it.
It is used
Math.floor
because that ensures us an integer in the required range.toFixed(n)
round, so we can get out of range if the first decimal is 5 or higher.Math.random()
it includes the 0 but not the 1, we have to correct that. If we add 1 to the amplitude we have a range of [min, max+1), but precisely having usedMath.floor
will eliminate any value above max.Let's see an example: with min=2 and max=5:
The values that we obtain before truncating will go from 2 to 5.99999..., with which we always have values in the desired range and homogeneously distributed (provided that the implementation of
Math.random()
is good)Actually, when doing
random
, we are dividing an integer so that the result is between the interval 0 (inclusive) and 1 (exclusive).If the program is compiled in 32 bits, multiply the result by 2 32 , and if it is compiled in 64 bits, it can be multiplied by 2 52 . For this, we use
Math.pow
, or directly, the result of that multiplication.Adding 1 is so that in an interval, for example, between 5 and 10, it accepts 10, that is, 10 is inclusive.
The code to extract a random number between two numbers should actually be the following. In this case it is between 5 and 10.