Currently making a program for homework and I am confused regarding one aspect of the normal formula that is usually used
Math.random() * (max - min) min
I understand that this would work perfectly fine with a range of 1 - 1000 for example.
Now, sorry for my ignorance and if this comes out as a stupid question... but if I want a range from 0 - 1000, would this still work?
Since the range 1 - 1000 would set (max - min) as 999, then multiply by Math.random() and then add min... range 0 - 1000 would set (max - min) as 1000 and would not add anything at the end since its still 0. Would this still work if I have min as 0 and max as 1000? Or would I have to go through a different route/formula?
CodePudding user response:
Let's break down the formula to see if it helps!
Given that Math.random() returns a double which has value 0 <= value < 1, when:
min = 1, the formula returns values between 1 (0 * (1000 - 1) 1 = 1) and 999 (0.999999... * (1000 - 1) 1 = 999)min = 0, the formula returns values between 0 (0 * (1000 - 0) 0 = 0) and 999 (0.999999... * (1000 - 0) 0 = 999)
So, min = 0 works as you'd expect but it seems like you're missing a 1 in the formula's range term:
Generating an integer random number in a range with Math.random() is done by this formula:
(int)(Math.random() * ((max - min) 1)) min
CodePudding user response:
Math.random() returns random nr range 0 to 1, so to get range 0 to 1000 all you need to do is to multiply by 1000. No need to add anything, so the formula will still work
