Skip to content
Advertisement

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; i.e., 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?

Advertisement

Answer

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().

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement