0

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?

Robotnik
  • 3,643
  • 3
  • 31
  • 49
  • 2
    you only need to know what `Math.random()` does ... the `* 10 + 1` is elementary level maths - when in doubt [read the documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) – Bravo Jun 23 '22 at 06:07
  • `Math.random() * 10 + 1` generates a random number between ( 0 - 10 ) + 1 – ahsan Jun 23 '22 at 06:11
  • `Math.random()` will return a float `0 - 0.99999999` (less than 1) so `* 10` is `0 to 9.999999` then `+ 1` is `1 to 10.99999999`, and rounded down is `1 to 10` – zer00ne Jun 23 '22 at 06:18

2 Answers2

4

Math.random returns a floating point number x such that:

enter image description here

Multiplying 10 to x yields a floating point number in the range:

enter image description here

And then adding 1 to 10x yields a floating point number in the range:

enter image description here

And finally flooring 10x + 1 yields an integer in the range:

enter image description here

Therefore, Math.floor(Math.random() * 10 + 1) yields an integer that lies in the range [1, 10].

SSM
  • 2,855
  • 1
  • 3
  • 10
1

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

Vidal Tan
  • 53
  • 4
  • Keep in mind that any time you do the 'Math.floor(Math.random()*num)' that whatever your num is means your range is 0-num not including num. So when you add something to that, you are increasing both the start and end of the range. – Vidal Tan Jun 23 '22 at 06:19