Why is this subtraction non-zero?

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.

+7
java math floating-point coldfusion
source share
7 answers

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.

+16
source share

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 .

+7
source share

Use PrecisionEvaluate() in ColdFusion (it will use BigDecimal in Java)

 zero = PrecisionEvaluate(416582.2850 - 411476.8100 - 5105.475); 

unlike Evaulate() , "" is not required.

+5
source share

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.

+2
source share

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 
+2
source share

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).

+1
source share

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 
+1
source share

All Articles