2

This is so silly I'm almost afraid to ask. But here goes.

> b <- c( 0.54, 0.56, 0.58, 0.6 )
> s <- seq( 0.54, 0.60, 0.02 )

I would expect these two to be equal and yet...

> b == s
[1] TRUE  TRUE FALSE  TRUE

What gives? I must be missing something really dumb. By the way, I had a colleague reproduce the same on his machine. I'm using

> sessionInfo()

R version 3.0.0 (2013-04-03)
Platform: x86_64-w64-mingw32/x64 (64-bit)

locale:
[1] LC_COLLATE=English_Canada.1252  LC_CTYPE=English_Canada.1252                     LC_MONETARY=English_Canada.1252
[4] LC_NUMERIC=C                    LC_TIME=English_Canada.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
[1] tools_3.0.0

A detail about the behaviour of seq in the docs, maybe?

Updated: See answer below and here. The lesson: Never forget that it's all floating point arithmetic.

Community
  • 1
  • 1
vathymut
  • 1,017
  • 2
  • 13
  • 25

1 Answers1

2

Try using all.equal function

> all.equal(b,s)
[1] TRUE
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
  • 1
    to clarify, the values aren't stored exactly how you may think. You can see what r is testing with `==` by viewing `data.frame(b = format(b, nsmall = 20), s = format(s, nsmall = 20))`. Clearly they are not *exactly* equal, but meh so-so equal. and that is what `all.equal` returns, "near-equality." – rawr Apr 04 '14 at 20:59
  • @rawr that's the bit that was puzzling me. The example helped. Thanks. – vathymut Apr 04 '14 at 21:12