I tried this function to find a random int number between two bonds, I know the method of Math.floor () and Math.random()
how works, but I could not understand the logic with this function (max-min + 1)
and the addition of min
. why do we need to use (max-min+1)
then the addition ofmin
?
function random(min, max) {
const num = Math.floor(Math.random() * (max - min + 1)) + min;
return num;
}
console.log(random(5, 10));
2
Answers
The purpose of
(max - min + 1)
is to determine the total number of possible values within the specified range, and it ensures that when you multiply it byMath.random()
, you consider all the integers within that range. Adding 1 is crucial to include the upper bound of the range.For example, if you want to generate random numbers between 3 and 6 (inclusive). The range is 3, 4, 5, 6. If you only calculate
(max - min)
, it would be(6 - 3)
, which equals 3. Without adding 1, you would have a range of 3 different values (3, 4, 5), and the upper bound (6) would be excluded.By adding 1 to the calculation
(max - min)
, you get (6 – 3 + 1), which equals 4. Now, you have a range of 4 different values (3, 4, 5, 6), including the upper bound.Well this is something you don’t generally get at the beginning, so let’s break it down:
Note: this calculation might be numbers less than your lower bound.
Now let’s go through your code:
The upper bound is 10
The lower bound is 5
Math.random generates a pseudo-float e.g 0.5
Hope this give a better understanding of the problem.