Why Math.floor which needs * 2 instead of Math.round?


#1

Why not use Math.round instead so that the *2 wouldn't be necessary?

When is Math.floor usually used - any practical examples?


#2

When you're dealing with integer values lets say you want to calculate how many people fit in an elevator if the answer is 5.789 than the answer is probably 5.

And for Math.round yes would be possible but I guess in this case one would need to explain when it rounds. Really idk.


#3

I had the same thought. You could just do Math.round(Math.random()), which is more elegant. I'm wondering if there is some reason why this wouldn't work as well, if it was an oversight on their part, or they just like the floor method?


#4

Math.floor is used so that each number has the same odds of appearing. For instance:

Math.floor(Math.random() * 3) // Produces 0, 1, or 2

if math random produces any value from 0 to 0.9 --> 0 will be the return value once floored
if math random produces any value from 1 to 1.9 --> 1 will be the return value once floored
if math random produces any value from 2 to 2.9 --> 2 will be the return value once floored

Math.round(Math.random() * 2) // Produces 0, 1, or 2

if math random produces any value from 0.0 to 0.4 --> 0 will be the return value once floored
if math random produces any value from 0.5 to 1.4 --> 1 will be the return value once floored
if math random produces any value from 1.5 to 1.9 --> 2 will be the return value once floored

Notice that with Math Round your chances of getting 0 and 2 are less than your chances of getting the number 1. However with Math Floor each number has the same odds of appearing.
Hope that helps.