I came across these values ββin my ColdFusion code, but the Google calculator seems to have the same βerrorβ where the difference is not zero.
416582.2850 - 411476.8100 - 5105.475 = -2.36468622461E-011
http://www.google.com/search?hl=en&rlz=1C1GGLS_enUS340US340&q=416582.2850+-+411476.8100+-+5105.475&aq=f&oq=&aqi=
JavaCast'ing for long / float / double does not help - this leads to other non-zero differences.
This is because decimal numbers that βlookβ around base 10 are not exactly represented in base 2 (this is what computers use to represent floating point numbers). See Article What Every Computer Scientist Should Know About Floating-Point Arithmetic for a detailed explanation of this problem and workarounds.
Floating-point inaccuracies (there is an infinite number of real numbers and only a finite number of 32- or 64-bit numbers to represent them with).
If you cannot handle tiny errors, you should use BigDecimal .
BigDecimal
Use PrecisionEvaluate() in ColdFusion (it will use BigDecimal in Java)
PrecisionEvaluate()
zero = PrecisionEvaluate(416582.2850 - 411476.8100 - 5105.475);
unlike Evaulate() , "" is not required.
Evaulate()
Since the computer stores numbers in binary, floating point numbers are inaccurate. 1E-11 is a tiny difference due to rounding these decimal numbers to the nearest representable binary number.
This βerrorβ is not an error. This is how floating point arithmetic works. See: http://docs.sun.com/source/806-3568/ncg_goldberg.html
If you want arbitrary precision in Java, use BigDecimal :
BigDecimal a = new BigDecimal("416582.2850"); BigDecimal b = new BigDecimal("411476.8100"); BigDecimal c = new BigDecimal("5105.475"); System.out.println(a.subtract(b).subtract(c)); // 0.0
The problem is the inaccurate representation of floating point types. Since they cannot be accurately represented as floating, you get some loss of accuracy, which leads to small errors in operation. Usually with floats you want to compare whether the result is equal to another value within a small episode (error rate).
These are floating point issues, and BigDecimal will fix this.
Changing the subtraction order also leads to zero in Google.
416582.2850 - 5105.475 - 411476.8100 = 0