5

While writing the following code in R:

seq1 <- seq(from = 0.05, to = 0.5, by = 0.05)

and then running the following code:

seq1 == 0.15

I get the following output:

FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE

When ideally I should be getting:

 FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE

The funny thing is if I say:

seq1 == (0.1+0.05)

Then I get the desired output:

FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE

What could be the problem?

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
Jash Shah
  • 2,064
  • 4
  • 23
  • 41
  • 8
    This is due to floating point arithmetics. It is never safe to compare floating point values with `==`. Use `all.equal()`instead. More information [here](http://stackoverflow.com/q/9508518/4770166). – RHertel Jul 19 '16 at 13:44
  • Or `dplyr::near()` to have it vectorized. – Axeman Jul 19 '16 at 15:06
  • 1
    Please only use the `rstudio` tag if your question concerns the RStudio code editor. You wouldn't use a `pen-and-paper` tag when asking a question about grammar! – Gregor Thomas Jul 19 '16 at 17:56

0 Answers0