#1

Dragon Slayer

I am just curious about the behavior of Math.random(). My question is, why do you need to add 1? For example:
Wouldn't

``Math.floor(Math.random() * 5 + 1);``

Be the same thing as:

``Math.floor(Math.random() * 6);``

?

I am trying to understand the practicality behind adding one to include 5 as opposed to just multiplying by 6.

#2

Not really because `Math.random()` return a random number by default between 0 inclusive and 1 exclusive.

So if you got 0.5 from math random and by doing the math you have `0.5*5` = 2.5 + 1 = 3.5
while on the other hand you would get `0.5 * 6` = 3

Even with the math floor, end results are different between those 2 statements.
My example of Math.random() outputting 0.5 is low chance to happen so it is not solid statement to hold but try writing in editor:

`console.log(Math.floor(Math.random() * 5 + 1));`
and
`console.log(Math.floor(Math.random() * 6));`

When you run the code you will see how different results are outputed

#3

On the surface they look the same, but the big difference is that the first example (with +1) will never be 0 (zero). The second example can be 0.

``````... * 5 + 1   // {1, 2, 3, 4, 5}

... * 6       // {0, 1, 2, 3, 4, 5}``````

#4

This makes sense! In this situation we wouldn't want 0 to be a possible outcome. Thank you for your insight!

#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.