Generate Random Whole Numbers within a Range- help me


can’t under stand the formula

Math.floor(Math.random() * (max - min + 1)) + min

Math.random() generates a random number where n>=0 and n<1, with lots of decimal points. To expand that out, to a range of numbers, we multiply it by the top number we want. To generate a number between 0 and 10, we would:

Math.random()*10 ;

That would give us a floating point number n>=0 and n<10. If we want to get an integer, we can apply

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

That rounds it down so we get an integer such that n>=0 and n<=9 (Since the highest 10% of numbers are 9.x, they will round down to 9.) If we want them to be from 1-10, we have to add 1:

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

If you can follow that, then you can probably understand your formula. the (max-min) just makes sure it is the right range, and the + min just makes it start at the right place.

1 Like

Although I question if the +1 should be inside the parentheses, but should be at the end.

{correction} Nope! I was wrong, that doesn’t work. Your formula is the right one.

Thanks for the explanation. I looked all over and can’t find a way to figure out what this formula means.