How does Math.random () generate random numbers outside of this "native" range?
I realize 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 int truncates everything after the decimal point without rounding.
I don't understand how something like
System.out.println((int)(Math.random() * 27));
can actually produce a random number between 0 and 26. Since Math.random()
by itself only produces 0.0 - 0.9 and 9 * 27 - 24.3, it seems that the largest int the code above should have should be 24. How does this work?
Through searching for answers to this, I discovered that there are better ways to generate random numbers, but the book I am processing describes this particular method and I would like to understand how it works.
source to share
The range is Math.random()
not 0.0
through 0.9
, it is 0.0
through the maximum possible double
less 1.0
, about 0.9999999999999999 or so.
Return:
pseudo-random twin 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 doing int
, you get 26
.
source to share
Since Math.random () by itself produces 0.0 to 0.9
This statement is incorrect. Math.random()
produces a random number in the range [0, 1). This means the upper bound is not 0.9 - it can produce 0.99, 0.999, 0.9999, or any decimal number arbitrarily close to 1. As an example, it 27 * 0.99
is 26.73, which shortens to 26
.
source to share
You are reading the specs wrong Math.random
.
The number that can be generated is between 0.0
(inclusive) and 1.0
(exclusion) . But it can also produce something 0.99999
ish.
Since you are multiplying with 27
, it will give you a number between 0.0
(inclusive) and 27
(exclusive). Thus, the maximum number that can be generated is 26.99999999...
.
Later in the process you make a throw to an integer: (int)
. This cast takes an integral part , so although the result can be 26.999999...
used 26
.
One final note is that Java has a decent class Random
that provides some functionality for generating integers. For example nextInt
, where you can specify the maximum (exclusive) number.
source to share