Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't (int) Math.random()*10 produce 10 in Java?

Tags:

java

Why the following produce between 0 - 9 and not 10?

My understanding is Math.random() create number between 0 to under 1.0.

So it can produce 0.99987 which becomes 10 by *10, isn't it?

int targetNumber = (int) (Math.random()* 10);
like image 357
shin Avatar asked Jun 22 '10 09:06

shin


3 Answers

Casting a double to an int in Java does integer truncation. This means that if your random number is 0.99987, then multiplying by 10 gives 9.9987, and integer truncation gives 9.

like image 106
Greg Hewgill Avatar answered Oct 20 '22 18:10

Greg Hewgill


From the Math javadoc :

"a pseudorandom double greater than or equal to 0.0 and less than 1.0"

1.0 is not a posible value with Math.random. So you can't obtain 10. And (int) 9.999 gives 9

like image 36
Agemen Avatar answered Oct 20 '22 17:10

Agemen


Cause (Math.random()* 10 gets rounded down using int(), so int(9.9999999) yields 9.

like image 24
Thariama Avatar answered Oct 20 '22 18:10

Thariama