How does Math.floor() in the 'Race Day' exercise work?

Hey, everyone!
In the Race Day exercise of the JavaScript course there’s a function provided by Codecademy at the beginning:

let raceNumber = Math.floor(Math.random() * 1000);

The hint of the exercise says:

Math.random() returns a value between 0 (inclusive) and 1 (exclusive).

In order to make this set of numbers range from 0 (inclusive) to 1000 (exclusive) we can multiply the returned value by 1000.

Finally, to ensure we only have whole numbers from 0 to 999 we can round down using Math.floor().

I have 2 questions:

  1. Why 1000 is not gonna be included in the random numbers generated? Because if Math.random() picks 1, the result will be 1 * 1000.
  2. What do inclusive and exclusive mean on the explanation?

Thanks in advance!

The floor of a number is the nearest integer less than the number. We are essentially truncating the whole number portion (removing the decimal fraction).

3.14   =>  a JS float

3      =>  the floor of 3.14

Recall that Math.random() generates only a decimal fraction (a float) less than 1, but possibly equal to zero, or anything in between.

Eg.

0.8503869061523449

The above is a typical random number returned from the Math.random() method. As it stands, it is less than 1 so if we floor it we end up with zero, no matter what it is. That’s all that is left over after truncation. 0.

If we multiply the float by a number greater than one we will have at least one digit to the left of the decimal point.

2 * 0.8503869061523449  ==  1.7007738123046898

Well, that is unless the number is less than 0.5. This will still be less than 1 when multiplied by 2. The net effect when we floor the result is either 0 or 1.

    y = Math.floor(Math.random() * 2)
    // { y | y is Integer and y is a member of [0, 1] }

It’s possible that multiplying by any number will still result in a value less than 1. That makes a floor value of zero always possible. We can therefore take measures to offset the floor value by some amount, 1 or more.

Eg.

r = Math.floor(Math.random() * 6) + 1

Above the floor value will be 0..5 and the offset we’ve given is +1. That gives us a typical roll of the die. One to six, inclusive.

Thanks for your clarification, Roy!
I still have a long way to learn all this, though.

1 Like

Take it slow, and question everything, even this same topic. Spend some time in the console playing with this. How could we give the same functionality to negative numbers?

1 Like

I realized that if we’re working with negative numbers, what the rounding down Math.floor() does is ahead of the integer. For example:

console.log (Math.floor(-5.95)); // Prints 6

You mean, -6? The floor will always be less than the number we start with, unless it is already integer. Be careful not to confuse this with rounding. That works on a different principle.

1 Like

Yes, I meant -6. :stuck_out_tongue_winking_eye: Thanks again, Roy!

1 Like