0

Why does the following code not return zero?

sum(c(-2.8, -1.8, -0.8, 1.2, 4.2))
2.220446e-16

It returns an extremely small value, but the answer is clearly zero, not close to zero. Why does this happen and How to deal with this problem?

Phil
  • 7,287
  • 3
  • 36
  • 66
Dom Jo
  • 320
  • 1
  • 3
  • 13
  • [\[r\] faq #4](https://stackoverflow.com/questions/9508518/why-are-these-numbers-not-equal) – Wimpel Mar 31 '21 at 16:36
  • @Wimpel Im not a computer person, so may be you can explain in some layman language – Dom Jo Mar 31 '21 at 16:38
  • 2
    @DomJo: google "floating point errors".. Computers are not always as accurate as we think. They do very well at what they are told to do and can do it very fast. But in many cases, a small inaccuracy can have dramatic consequences. A very well-known problem is floating point errors. Floating point numbers have limitations on how accurately a number can be represented. The actual number saved in memory is often rounded to the closest possible value. The accuracy is very high and out of scope for most applications, but even a tiny error can accumulate and cause problems. – Wimpel Mar 31 '21 at 16:41
  • 2
    also, from *the R inferno*: "Whenever floating point operations are done—even simple ones, you should assume that there will be numerical error. If by chance there is no error, regard that as a happy accident—not your due. You can use the `all.equal` function instead of `8 == 8` to test equality of floating point numbers. If you have a case where the numbers are logically integer but they have been computed, then use `round` to make sure they really are integers." – Wimpel Mar 31 '21 at 16:48
  • Adding to @Wimpel's comments, you can also compare the result to your machine's implementation of [Epsilon](https://en.wikipedia.org/wiki/Machine_epsilon), the upper bound of rounding error in floating point arithmetic, with `sum(c(-2.8, -1.8, -0.8, 1.2, 4.2)) < .Machine$double.eps^0.5`. If the comparison returns `TRUE` you can conclude the result is within the limits of floating point rounding error. – Len Greski Mar 31 '21 at 16:55

0 Answers0