7

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);
shin
  • 31,901
  • 69
  • 184
  • 271
  • You should be using Random.nextInt() to get "better" random numbers anyway: http://stackoverflow.com/questions/738629/math-random-versus-random-nextintint/738651#738651 – Goibniu Jun 22 '10 at 10:10

8 Answers8

19

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.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
14

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

Agemen
  • 1,525
  • 9
  • 18
2

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

Thariama
  • 50,002
  • 13
  • 138
  • 166
1

Because (int) rounds down.
(int)9.999 results in 9. //integer truncation

Community
  • 1
  • 1
Kobi
  • 135,331
  • 41
  • 252
  • 292
0

0.99987 which becomes 10 by *10

Not when I went to school. It becomes 9.9987.

user207421
  • 305,947
  • 44
  • 307
  • 483
0

Math.floor(Math.random() * 10) + 1

Now you get a integer number between 1 and 10, including the number 10.

0

You could always tack on a +1 to the end of the command, allowing it to add 1 to the generated number. So, you would have something like this:

int randomnumber = ( (int)(Math.random( )*10) +1);

This would generate any integer between 1 and 10.

If you wanted any integer between 0 and 10, you could do this:

int randomnumber = ( (int)(Math.random( )*11) -1);

Hope this helps!

arsb48
  • 563
  • 4
  • 10
0

you can add 1 to the equation so the output will be from 1 to 10 instead of 0 to 9 like this :

int targetNumber = (int) (Math.random()* 10+1);
Littlefoot
  • 131,892
  • 15
  • 35
  • 57
Shatha AR
  • 5
  • 4