In some coding practice websites, I found below assignment operation for generating a random whole number that falls within a range of two specific numbers.
To do this, we’ll define a minimum number min and a maximum number max.
Here’s the formula we’ll use. Take a moment to read it and try to understand what this code is doing:
Math.floor(Math.random() * (max - min + 1)) + min
This formula is bit ambiguous to me. Could anyone please explain the logic.
Advertisement
Answer
Let’s break this:
- First lets look at
Math.random()
. According to here
The
Math.random()
function returns a pseudo-random number in the form of a floating point number in the range from 0 – 1 (including 0, but not 1)
- Multiply it by
(max - min + 1)
will give youoffset
in the range betweenmin
andmax
and will make sure you won’t exceed this limit. - Adding
+ min
will make sure you get the shifting from [0 tooffset
] to [min tooffset + min
] which we said is limited bymax
. - Finally
Math.floor
to make it integer number instead of float (its floor and notMath.ceil
because the originalMath.random()
is not including the1
).