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


#1

* Math.floor(Math.random()5+1)**
why is the range between 1 and 5 (up to and including 5), instead of between 1 and 6 (up to and including 6)??

If Math.random() creates a number 1, timesing 5 and +1 will give out 6 won't it???


#2

Till the second step, you have created a real number (number with decimal parts) x such that 0 <= x < 5.
Now, on the third step, since you use Math.floor, the range becomes only one of the numbers in [0, 1, 2, 3, 4]. How, you ask? Because all numbers like 0.0001, 0.23, etc. get converted to 0, all numbers like 1.123, 1.63, etc. get converted to 1, all numbers like 2.034, 2.77, etc. get converted to 2, all numbers like 3.876, 3.234, etc. get converted to 3 and all numbers like 4.9999999, 4.00001, etc. get converted to 4.

Then finally, we add 1 to that x to make its possible values from [0, 1, 2, 3, 4] to [1, 2, 3, 4, 5]

This is the explanation of that entire paragraph and thus I hope it resolved your issue. Note that the range of any number x created by Math.random() is 0 <= x < 1. Math.random() never returns 1.

Hope it helps!


#3

Why does it floor the Math.random() * 5 before adding the 1? They are both in the parenthesis, so shouldn't the 1 be added before the value is floored?


#4

Excellent question @epistemic! If you would go by the hint's instructions alone, you would get what I told you - Math.floor(Math.random() * 5) + 1. However, the hint should have given instructions for the code sample given in it - Math.floor(Math.random() * 5 + 1)

I will communicate this to the staff. Thanks for noticing!

(reference: Exercise link)


#5

'from 0 up to 1' doesn't include 1?


#6

No. When in doubt, refer docs.