If Math.Random() ranges

Im a bit further than the introduction but have still encountered the need for Math.Random, and while I was using it I started to get confused.

if Math.floor(Math.Random()) results in either 0 or 1,
then wouldn’t Math.floor(Math.Random *3)) give you either 0 or 3?

[0 x 3 = 0 and 1 x 3 = 3]

I know that what you actually get is a range between 0 and and 3 but how?


is in the range of 0 to 1, the zero inclusive, the 1, exclusive.

Note that it is random not Random. Also note, it is not an either/or method. It is any float including zero, that is less than 1.

Given it never reaches 1, multiplying by any value will never give back that value, only a float that is less than it.

Math.random() * 10

can never reach 10.

1 Like

To add to the other comment.
Math.random() is generating a number between 0 and up to, but not including 1 (i.e. 0 → 0.9999…).
Math.floor(…) will lower the number it takes down to the nearest integer. (i.e. ignore any decimal part to give a whole number)
So, using;
as is, would always result in 0.

So, for;
Math.floor( Math.random() * 3 )

First, it does Math.random() and gets a number between 0 and 0.999…
Then it takes that number and multiplies it by 3.
That gives you a number between 0 and 2.999…
Then Math.floor removes the decimal part to leave you with an integer. Which, in this case, would be 0, 1 or 2

Hope that helps.