Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this subtraction not equal zero?

I happened upon these values in my ColdFusion code but the Google calculator seems to have the same "bug" where the difference is non-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 these to long/float/double doesn't help- it results in other non-zero differences.

like image 832
Brian Pan Avatar asked Jan 04 '10 22:01

Brian Pan


People also ask

Why can't you subtract a number from zero?

Like addition, if you subtract 0 from any number, you get the same sum. For example, 12-0 = 12. If you're subtracting, you may need to use borrowing to solve the problem.


1 Answers

This is because decimal numbers that "look" round in base 10, are not exactly representable in base 2 (which is what computers use to represent floating point numbers). Please see the article What Every Computer Scientist Should Know About Floating-Point Arithmetic for a detailed explanation of this problem and workarounds.

like image 141
Greg Hewgill Avatar answered Oct 12 '22 14:10

Greg Hewgill