Is this a glitch in Java?
I go to solve this expression: 3.1 - 7.1
I get the answer: -3.9999999999999996
What is going on here?
A great explanation can be found here. http://www.ibm.com/developerworks/java/library/j-jtp0114/
Floating point arithmetic is rarely exact. While some numbers, such as 0.5, can be exactly represented as a binary (base 2) decimal (since 0.5 equals 2-1), other numbers, such as 0.1, cannot be. As a result, floating point operations may result in rounding errors, yielding a result that is close to -- but not equal to -- the result you might expect. For example, the simple calculation below results in 2.600000000000001, rather than 2.6:
double s=0; for (int i=0; i<26; i++) s += 0.1; System.out.println(s);
Similarly, multiplying .1*26 yields a result different from that of adding .1 to itself 26 times. Rounding errors become even more serious when casting from floating point to integer, because casting to an integral type discards the non-integral portion, even for calculations that "look like" they should have integral values. For example, the following statements:
double d = 29.0 * 0.01; System.out.println(d); System.out.println((int) (d * 100));
will produce as output:
0.29 28
which is probably not what you might expect at first.
See the provided reference for more information.
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