Generating random number between two given numbers


I am following some tutorial at treehouse and had to create a program that generates a random number between two given numbers. I found a formula using math.random from mozilla and they don’t explain how it really works. Anybody dare to explain it to me? Newbie here.

function getRandomArbitrary(min, max) {
  return Math.random() * (max - min) + min;

I am confused as to how that really works.

Thank you very much.


Hey @nelsonaj!

Math.random() returns a floating-point, pseudo-random number in the range 0–1 (inclusive of 0, but not 1).

So in your function above, let’s say you want to return a random number between 2 and 10.

Math.random() is – let’s say – 0.5. We’re doing the following in the function:

0.5 * (10-2) + 2

We want our random number to be between 0 and 8, and we add that random number to the lower number (2).

0.5 * 8 gives us that random number.

Let me know if this helps, or if I can clarify further!


Thank you @lpatmo that helps. I was confused as to why subtract the lowest from the highest number and then add it back again, but now I see why. Thank you again!