-1

Look at this simple R code:

seq(0.3, 2, 0.01)[56]
## [1] 0.85  
seq(0.3, 2, 0.01)[56] == 0.85
## [1] FALSE  

Why do I get this and what's the best way to do such equality test?

David Arenburg
  • 87,271
  • 15
  • 123
  • 181
ywx
  • 127
  • 1
  • 7

1 Answers1

1

You need to use all.equal as in

all.equal(seq(0.3, 2, 0.01)[56],0.85)

This occurs because of issues in representing numbers less that 1 in binary. In general, 0.85 cannot be written exactly in binary, and the approximation used by simply typing 0.85 is not identical to the approximation used by adding an approximation of 0.01 to an approximation of 0.3 55 times.

For more details see here: Why can't decimal numbers be represented exactly in binary?

Community
  • 1
  • 1
John Paul
  • 10,536
  • 6
  • 53
  • 69
  • That makes sense.> print(seq(0.3, 2, 0.01)[56], digits=17) [1] 0.85000000000000009 > print(0.85, digits=17) [1] 0.84999999999999998 – ywx Aug 25 '14 at 14:57
  • 1
    "In R 0.85 cannot be written exactly in binary" That's not R specific. – Roland Aug 25 '14 at 15:05