Reputation: 2692
I am surprised to see below difference in Java:
(double)(int1/int2) // return 0.0 - precision lost.
(double)int1/int2 // return 9.3123325E-10 - precision kept.
Is it by design that the bracket in the first expression makes the evaluation lose the precision?
Upvotes: 1
Views: 470
Reputation: 106400
It's a matter of order-of-operations. Parentheses have a higher priority than casts, so your first statement will perform the operations in the parentheses first - it casts the quotient to a double
.
Casts have a higher priority than division, so in your second statement, the cast is applied before the division operation.
Upvotes: 2
Reputation: 136
I believe this has to do with the fact that parenthesis (per PEMDAS) causes the calculation to happen within the parenthesis before the cast occurs and as such, the decimal value if the division is less than 1 is 0.
Example:
(double) (3/5) = (double) 0; (Since Int can't be .6)
But (double) 3/5 --> (double) .6
Upvotes: 0
Reputation: 2969
Absolutely. In statement 1 you do the division and then cast. In statement 2 you first cast int1 to a double, then you do division which promotes int2 to a double and precision is kept.
I don't intend this to sound snarky, but the language (and compiler) is doing what you asked it to do. :)
Upvotes: 1
Reputation: 8116
Because of the brackets (double)(int1/int2)
first performs integer division (precision lose included) and then casts the result to double.
The (double)int1/int2
performs a double division because the first operand is double.
Upvotes: 1
Reputation:
In the first one, you're doing integer division, then casting to double. Since integer division truncates any decimals, you're losing the decimal bit of the answer, and casting it to double doesn't bring that info back.
In the second, you're casting the top one to double, then doing double division. This makes the answer automatically a double, since it takes the higher-precision unit when dividing, and ensures that you're getting the decimal bit too.
The second is equivalent to ((double) int1) / int2
, since casts have higher precedence than /
.
Upvotes: 0
Reputation: 2446
Yes, it's by design. By putting the expression in parens, you're modifying the normal precedence, so int1/int2
will execute first, and because both are (presumably) integers, use integer division, which will truncate the result to an integer. In the second case, the normal precedence applies, so int1 is being converted to a double first, then the division done using floating point division.
Upvotes: 2