Math.random()
generates series of decimal numbers from 0(inclusive) to 1(not inclusive). So we can have numbers like 0.21724877044031787, 0.814708270731549 and so on.
So, we need to convert these numbers to whole numbers in a specified range. We'd pick 3 to 7 here.
How can we do that ? πππ
We need to multiply the random number with a number. I know it might not sound so cool, like "why not just multiply it with 2 or 5 or 7", but it's a lot more than that because we need the number to be in the specified range.
And that number actually is (MAX - MIN + 1) + MIN
= (7 - 3 + 1) + 3
Huh?? WTH is that??
Don't panic, it's just like a sanity check... And please, keep the addition MIN
to yourself for now. I'll explain below.
Let's say we use our generated randoms (0.21724877044031787 and 0.814708270731549), then multiply them by 10, we'd have 2.172*** and 8.147***
. Remember Math.random generates from 0
to 0.99***
, so we can't have a 10 when multipled by 10... Hmm, So when Math.floor
is applied, we'll have numbers from 0 to 9.
To make the last number inclusive(which is 10), we'll need to add 1, right?? That calls for the 1 in (MAX - MIN + 1)
I think we just diversed to 10, yeah, 10 is cool for these kinda things π
Let's say we want to start our count from 2, you'd probably say "Yeah, 10 gave me numbers from 0 to 10, so it's like saying 0 is minimum here and 10 is maximum, so lets just say the formula for that is RandomNumber * (10 - 2 + 1)
" but its totally wrong.
Deducting 2 from 10 actually cut off the balance, so instead of generating numbers starting from 2 and end in 10, it generates numbers from 0 to 8, so we need to balance it up by supplying the deducted 2
. That's the reason for the added MIN
.
So, all these crap led to the derived formula:
Math.floor(Math.random() * (MAX - MIN + 1)) + MIN;
Thanks for checking this out! If it need improvements, pls feel free to share :)