1

Possible Duplicate:
Why are these numbers not equal?

in Gnu R:

which(seq(0, 1600, 0.05) == 0.3) returns
integer(0)

but this:

which(round(seq(0, 1600, 0.05),2) == 0.3) returns
[1] 7

What happens with the seq() function?

Community
  • 1
  • 1
TWiSt_kid
  • 97
  • 3
  • 9

1 Answers1

5

That is essentially R FAQ 7.31 on comparisons between floats -- leading to the famous 'What every Computer Scientist should know about floating point numbers'.

In a nutshell, use identical() and other helper functions to compare relative to a small value \epsilon as perfect equality cannot be had with floating point types.

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
  • Can you elaborate on how to use `identical` here? e.g. This also gives `integer(0)`: `which(sapply(seq(0, 1600, 0.05), identical, 0.3))` – GSee Nov 15 '12 at 14:24
  • Which is why I waffled and and said _and other helper functions_ :) I wrote that on the train. Try this for size: `which(sapply(seq(0, 1, by=0.05), function(x) isTRUE(all.equal(x, 0.30))))` – Dirk Eddelbuettel Nov 15 '12 at 14:33
  • 2
    Or simply test for an entry that is "close" to 0.3 with `which(abs(seq(0, 1600, 0.05) - 0.3)<.001)` – Stephan Kolassa Nov 15 '12 at 14:54
  • @StephanKolassa, that's _much_ faster. – GSee Nov 15 '12 at 14:55
  • 1
    And that is the usual way to do it in any programming language. With eps equal to sqrt of float precision. – Dirk Eddelbuettel Nov 15 '12 at 14:57