Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java double precision with constant multiplication/division [duplicate]

Possible Duplicate:
Retain precision with Doubles in java

Do you know the difference between these two operations in Java.

final double m1 = 11d / 1e9; // gives 1.1e-8
final double m2 = 11d * 1e-9; // gives 1.1000000000000001e-8

I see in the generated bytecode that the precompiled result of m2 is already not what I expected.
In the output of javap -verbose -c I can see the following value :

const #3 = double   1.1E-8d;
[...]
const #6 = double   1.1000000000000001E-8d;

When I use m1 or m2 in other expressions, I don't have the same result.

When I try the same thing in C, m1 and m2 is strictly 1.1e-8

I think my problem is in the way java handles double precision computation but I can't explain myself what I miss.

like image 442
Joker Avatar asked Oct 07 '22 05:10

Joker


1 Answers

There is no difference between Java and C, both respect the IEEE floating-point standard. The only difference can be the way you print it. The exact number 1.1e-8 is not representable as a double. The difference in output may be attributed to the details on how the error of representation was accumulated, and to what rounding is used to print the result.

like image 119
Marko Topolnik Avatar answered Oct 12 '22 12:10

Marko Topolnik