java – Math. How does random () generate random numbers beyond the “native” range?
As far as I know, math Random () itself generates random doubles between 0.0 and 1.0, including 0.0 but not 1.0 I also understand that converting to int truncates everything after the decimal point without rounding
What I don't understand is
System.out.println((int)(Math.random() * 27));
You can actually generate a random number from 0 to 26 Because of math Random () itself only generates 0.0 to 0.9, while 9 * 27 is 24.3. It seems that the maximum int that the above code should be able to generate is 24 Does this work?
By searching for answers, I found a better way to generate random numbers, but the book I am writing describes this special method, and I want to know how it works
Solution
Math. The range of random() is not 0.0 to 0.9. It is 0.0 to the maximum possible double. It is less than 1.0, about 0.99999999999999
If you multiply the maximum possible result by 27 and truncate it by casting to int, you get 26