I came across the following command:
Math.floor(Math.random() * 10 + 1);
I understand that Math.floor()
will convert to the lowest integer, but what does Math.random() * 10 + 1
do?
I came across the following command:
Math.floor(Math.random() * 10 + 1);
I understand that Math.floor()
will convert to the lowest integer, but what does Math.random() * 10 + 1
do?
Math.random
returns a floating point number x
such that:
Multiplying 10
to x
yields a floating point number in the range:
And then adding 1
to 10x
yields a floating point number in the range:
And finally flooring 10x + 1
yields an integer in the range:
Therefore, Math.floor(Math.random() * 10 + 1)
yields an integer that lies in the range [1, 10]
.
Math.random generates a random number between 0 and 1. So for example it can be .124 or .42242. When you multiply this random number against something, you are basically making it so that the new result is no less than 0, but no more than the number you are multiplying it against.
So in your example, you are multiplying it against 10, which means you will get a random number between 0 and 10 with decimals; technically this range is 'more than 0, but less than 10'. The +1 just increases the total range so that it is between 1 and 11, or 'more than 1, but less than 11.
When you apply Math.floor() to this, you are rounding all of these results down. So in the case without the '+1', your finite range is actually 0-9, and with the +1 it is 1-10