In Mathematica 8 when I enter 1 - 0.99 - 0.01 I get 8.67362*10^-18 instead of zero. How do I fix this problem?

I am getting imaginary solutions because of this error in my program.

  • 1
    $\begingroup$ Have a look at Chop. $\endgroup$ – b.gates.you.know.what Jan 22 '13 at 9:35
  • 1
    $\begingroup$ When you input a number like 0.1 Mathematica will carry out computation using a floating point approximation to the number, this is done in order to gain speed at the sacrifice of accuracy. If you desire exact numbers you can use rationals: 1-99/100-1/100 => 0. Or you can simply account for approximation errors as b.gate suggest $\endgroup$ – jVincent Jan 22 '13 at 9:46
  • 3
    $\begingroup$ Suggested reading: "What Every Computer Scientist Should Know About Floating-Point Arithmetic" $\endgroup$ – Niki Estner Jan 22 '13 at 15:50
  • 1
    $\begingroup$ This is a very commonly asked about thing not only in Mathematica, but in just about any computer language. In short, the reason is that these numbers are represented in binary (e.g. 1/2 is 0.1 in binary, 1/4 is 0.01), and not every number that's representable in decimal is representable in binary (similarly to how 1/3 = 0.3333... is not exactly representable in decimal with a finite number of digits). E.g. when you type 1/10 = 0.1 in decimal, this is 0.1100110011001100... in binary. Because the machine works with a finite number of binary digits, precision suffers. $\endgroup$ – Szabolcs Jan 22 '13 at 17:36
  • 1
    $\begingroup$ Without having more context, it's difficult to determine which of many possible solutions would work. For instance, in many cases a simple change of the form N(1-99/100-1/100) would do the trick. Is this sort of solution acceptable or do you need some kind of automatic way to avoid floating point imprecision? $\endgroup$ – whuber Jan 22 '13 at 18:22

Browse other questions tagged or ask your own question.