Comparing floating point numbers

Problem

Comparing floating point numbers does not always work as you expect. For example:

  1. 0.3 == 3*.1
  2. #> [1] FALSE
  3. (0.1 + 0.1 + 0.1) - 0.3
  4. #> [1] 5.551115e-17
  5. x <- seq(0, 1, by=.1)
  6. x
  7. #> [1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
  8. 10*x - round(10*x)
  9. #> [1] 0.000000e+00 0.000000e+00 0.000000e+00 4.440892e-16 0.000000e+00 0.000000e+00
  10. #> [7] 8.881784e-16 8.881784e-16 0.000000e+00 0.000000e+00 0.000000e+00

Solution

There is no universal solution, because this issue is inherent to the storage format for non-integer (floating point) numbers, in R and computers in general.

See this page for more information and workarounds:http://www.mathworks.com/support/tech-notes/1100/1108.html. This is written for Matlab, but much of it will be relevant for R as well.