I understand that Math.random()
by itself generates a random double between 0.0 and 1.0, including 0.0 but excluding 1.0. I also understand that casting to an int truncates everything after the decimal without rounding.
What I don't understand is how something like
System.out.println((int)(Math.random() * 27));
can actually produce a random number from 0 through 26. Since Math.random()
by itself only produces 0.0 through 0.9, and 9 * 27 is 24.3, it seems like the greatest int the above code should be able to produce is 24. How does this work?
Through searching for answers to this I have discovered that there are better ways to generate random numbers, but the book I am working through describes this particular method, and I'd like to understand how it works.
The range of Math.random()
isn't 0.0
through 0.9
, it's 0.0
through the greatest possible double
less than 1.0
, about 0.9999999999999999 or so.
Returns:
a pseudorandom double greater than or equal to 0.0 and less than 1.0.
If you multiply the largest possible result by 27
and truncate it by casting to int
, you will get 26
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments