简体   繁体   中英

Rounding in Java using Math.random()

Suppose I write

System.out.println (Math.random()*5);

then one would obtain and output of x in [0, 4.9...]. But upon casting it as an integer, the result I continuously see (in my course) is [0, 4]. My question is how we are defining the rounding function; I am familiar with the floor function, and the floor of 4.9... is precisely 5 due to there existing no epsilon larger than zero satisfying the output x existing in some epsilon neighborhood; ie, the equality 4.9... = 5 suffices and because the floor of an integer is that integer, the result would be 5.

Where am I going wrong here?

Writing a new answer to address questions raised in comments. The output of Math.random() is in the range [0,1). The result will be a number strictly less than 1, so Math.random()*5 will give a result in the range [0,5), that is a number strictly less than 5. Since casting truncates, that means that your results will be in the integer set {0, 1, 2, 3, 4} with (approximately) equal probabilities for each of the five values.

Java: Math.random() Max Value (double just less than 1) has some more details on the math of the exact values that are possible with Math.random() .

When you cast to int like this

int i = (int) 4.9;

JVM will simply drop decimal places and you will get value 4 assigned to the variable. It is not rounding it is truncating,

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