1

When I do a simple calculation with R 3.0.1, I got the following results. My question is that why the value of the first and the third equations are not equal to 0?

> -0.0082 + 0.0632 - 0.055
[1] 6.938894e-18
> -0.0082 - 0.055 + 0.0632
[1] 0
> 0.0632 - 0.0082 - 0.055
[1] 6.938894e-18
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • See also http://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-doesn_0027t-R-think-these-numbers-are-equal_003f – Henrik Nov 28 '13 at 12:04

1 Answers1

6

Only a finite set of real numbers can be represented exactly as a 64-bit floating-point values (which is what you are using). As it happens, none of the three values in your example fall into that category:

> format(0.0082, digits=20)
[1] "0.0082000000000000006911"
> format(0.0632, digits=20)
[1] "0.063200000000000006173"
> format(0.055, digits=20)
[1] "0.055000000000000000278"

This means that all of the computations are inexact.

Of particular relevance to your example is the fact that floating-point addition is not associative.

For an excellent backgrounder, see What Every Computer Scientist Should Know About Floating-Point Arithmetic.

NPE
  • 486,780
  • 108
  • 951
  • 1,012