0

Ok so sometimes I seem to need to add 1 to one of the numbers like this:

Here I added 1 to left 10 so it would return number 10 to 20. including 10 to including 20.

Math.floor(Math.random() * 11) + 10;

Here adding 1 doesn't seem to be needed on left number as number returned is 2 to 9 ( I wanted returned number to be 2 to 8 including 2 and 8)

const randomNumber = Math.floor(Math.random() * 8) + 2;

can't understand when to add 1 to left number

  • 2
    You nowhere do `+ 1` in your code. You add `+ N` when you want to shift range by N, you multiply by `* M` when you want to set end of range to specific number. – Justinas Feb 21 '23 at 11:18
  • If you want to improve your understanding, the best thing you can do is experiment. You learn much more by doing than by being told. If you don't understand a complex operation, break it down into its atomic steps. You can see exactly what's going on here by performing each step of the calculation separately, and printing the results after each of those steps. – pjs Feb 21 '23 at 21:09

1 Answers1

1

_"added 1 to left 10" no, you scale the random value over the range of possible output values.

You want a result in the range 10 - 20 inclusive, which is 11 possible integer values so you multiply the random value, x, (0 <= x < 1) by 11 to get a value, n, such that, 0 <= n < 11. By flooring the result you get an integer between 0 and 10 (inclusive). You then add 10 to this to get a value in the range 0 - 20.

Following that same logic for your second example Math.floor(Math.random() * 8) + 2;

  • Math.random() * 8 - results in a number x where 0 <= x < 8.
  • Math.floor(x) - gives an integer between 0 and 7, inclusive.
  • + 2 - add an offset so the result is in the range 2 - 9.

To get a number between 2 and 8, you should change the initial 8 to 7 as you want a number in the range 2 - 8, which is one of 7 distinct integer values.

You shouldn't just add 1 without understanding the algorithm first. Once you do you can get a random integer between any 2 arbitrary numbers.

phuzi
  • 12,078
  • 3
  • 26
  • 50