简体   繁体   中英

How does Math.random() generate random numbers beyond it's “native” range?

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 .

Since Math.random() by itself only produces 0.0 through 0.9

This statement is incorrect. Math.random() produces a random number in the range of [0, 1). This means that the upper bound isn't 0.9 - it can produce 0.99, 0.999, 0.9999 or any decimal number arbitrarily close to 1. Just as an example, 27 * 0.99 is 26.73, which is truncated down to 26 .

You read the specifications of Math.random wrong.

The numbers that can be generated are between 0.0 (inclusive) and 1.0 (exclusive) . But it can also produce something 0.99999 ish.

Since you multiply with 27 it will give you a number between 0.0 (inclusive) and 27 (exclusive). The maximum number that can be generated is thus 26.99999999... .

Later in the process, you make a cast to an integer: (int) . This cast takes the integral part , so although the result can be 26.999999... , 26 is used.

A final remark is that Java has a decent Random class, that provides some functionality to generate integer numbers. For instance nextInt where you can give the maximum (exclusive) number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM