I'm wondering why floating point numbers in Java can represent exact value when they are initialized as literals, but they are approximate when they represent result of some calculation. For example:
double num1 = 0.3;
double num2 = 0.1 + 0.2;
System.out.println(num1);
System.out.println(num2);
why the result is:
0.3
0.30000000000000004
and not:
0.30000000000000004
0.30000000000000004
When there is no exact binary representation of 0.3. I know the BigDecimal class, but I don't quite understand this primitive numbers inconsistency.
None of the three numbers can be represented exactly as a double
. The reason that you get different results is that the value after adding 0.1
to 0.2
has a different representation error than 0.3
. The difference of about 5.5E-17 is enough to cause a difference when printing out the result (demo).
double a = 0.2;
double b = 0.1;
double c = 0.3;
double d = a+b;
double e = d-c; // This is 5.551115123125783E-17
When 0.3 is converted to its representation as ones and zeroes then converted back to decimal, it rounds to 0.3. However, when 0.1 and 0.2 are respectively converted to binary, the errors add up upon addition so as to show up when the sum is converted back to decimal. A thorough explanation would involve demonstrating the IEEE representation of each number along with the addition and conversions. A bit involved, but I hope you got the idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With