Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random int function

Tags:

Can someone explain why (int) (Math.random()*12-3) returns values between -2 and 8 while (int) (Math.random()*12)-3 returns between -3 and 8?

The difference is the placement of a parenthesis, but I don't know the "under the hood" reason why it makes a difference. If the lowest value that Math.random() can return is 0, that 0*12 = 0 and both should end up with -3 as a minimum. I assume it has to do with casting to an int and 0.x to 1. Is it just that it is (theoretically) impossible to hit 0.00000000...?

like image 924
Teed Ferguson Avatar asked Nov 29 '18 00:11

Teed Ferguson


1 Answers

The first one can return -3, it is just very unlikely.

Math.random():

Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.

So when you have (int) (Math.random()*12-3), inside the inner parentheses, the result will be a double, which you cast to an int. This truncates the decimal places, so unless Math.random() * 12 returns exactly 0 (And then once you subtract 3 to get exactly -3), Math.random() * 12 -3, will return at the lowest 2.{...}, and it will get truncated to -2.

When you do:

(int) (Math.random()*12)-3

The casting is of greater precedence than the subtraction, so it is greater likelihood to get truncated to 0. Then you subtract three, which results in -3.

like image 124
GBlodgett Avatar answered Oct 16 '22 15:10

GBlodgett