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 youoffsetin the range betweenminandmaxand will make sure you won’t exceed this limit. - Adding
+ minwill make sure you get the shifting from [0 tooffset] to [min tooffset + min] which we said is limited bymax. - Finally
Math.floorto make it integer number instead of float (its floor and notMath.ceilbecause the originalMath.random()is not including the1).