1

I know that there are plenty of posts on this topic, but I can't find any that explain clearly enough for me why the formula works the way it does.

On Mozilla's page to get a random number in (min, max), we have

function getRandomIntInclusive(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

But I don't understand how that is. If I take [4,10] for example,

r * (10 - 4) -> [0,6) // r to represent a random number in [0,1)
r * (10 - 4 + 1) -> [0, 7)
(r * (10 - 4 + 1)) + 4 -> [4, 11)

I don't know how that's supposed to give a random number in [4,10]. Could someone please explain?

Also, how do I get a random number in the open interval (a, b)?

TheRealFakeNews
  • 7,512
  • 16
  • 73
  • 114

0 Answers0