Java double precision with constant multiplication / division

Possible duplicate:
Keep precision with doubling 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 m2 is no longer the one I expected.
At the output, javap -verbose -cI 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 do not have the same result.

When I try to do the same in C, m1 and m2 are strictly 1.1e-8

I think my problem is how java handles calculations with double precision, but I cannot explain what I missed.

+5
source share
3 answers

, 1e9 1e-9, . , .

System.out.println(new BigDecimal(1e9));
System.out.println(new BigDecimal(1e-9));

1000000000
1.0000000000000000622815914577798564188970686927859787829220294952392578125E-9

, * /, , .

System.out.println(11 * 1e9);
System.out.println(11 * 1e-9);

1.1E10
1.1000000000000001E-8
+1

Java C, IEEE . , . 1.1e-8 a double. , , , .

+3

BigDecimal, :

BigDecimal a=new BigDecimal(1e-9);
BigDecimal b=new BigDecimal(11);
System.out.println(a.multiply(b).toString());

,

1.10000000000000006850975060355784206078677556206457666121423244476318359375E-8

JVM :

1.1000000000000001e-8
0

All Articles