JavaScript JavaScript Numbers The Math Object Create a Random Number

Max Primo
Max Primo
976 Points

So I was testing out the Math.ceil and Math.floor. But I never got 0 when I used Math.ceil. Mistake in the video?

So in the video it states that Math.ceil is not a good way to get a random number between 1-6 because you might end up with a zero. However, when I ran Math.ceil(Math.random()*6); I actually never got any zeros and they were all between 1-6.. Is this a mistake in the video? I am just confused. However, I did get 0 when I ran Math.floor(Math.random()*6); without adding the 1. But my point is that you can get 1-6 without adding the +1 if you just did Math.ceil?

1 Answer

Cameron Childres
MOD
Cameron Childres
Treehouse Moderator 11,682 Points

Hey Max~

This is not an error, there's just an incredibly small chance to receive a zero value.

When you run Math.random() you get a random number in a range that starts with 0 and approaches, but never reaches, 1. I just ran Math.random() a few times in my browser, here are some results:

  • 0.06402171468849871
  • 0.0485511979040667
  • 0.381454323282967
  • 0.2018132157678454

Running Math.ceil() on any of these numbers will return 1, since it always rounds a number up to the next largest integer. Now take for example this number:

  • 0.00000000000000001

This will also be brought up to 1 with Math.ceil() -- it's the next largest integer.

You'd get zero if the random number generated was precisely zero:

  • 0.0000000000000000

There's something like a one-in-one-hundred-thousand-million-million chance of this happening, I wouldn't expect you to see it in a quick test -- BUT, it is possible.

Max Primo
Max Primo
976 Points

Oh I see, thank you for clarifying!