0

I have been banging my head against this for a couple hours now, and I'm not any closer to understanding it. Why does the following R code return a value of FALSE?

any(seq(27.17,137.74,by=0.01) == 27.38)
[1] FALSE

seq(27.17,137.74,by=0.01)[22]
[1] 27.38

seq(27.17,137.74,by=0.01)[22] == 27.38
[1] FALSE

Whether R can find a given value in the sequence seems almost random:

seq(27.38,27.43,by=0.01) %in% seq(27.17,137.74,by=0.01)
[1] FALSE  TRUE FALSE  TRUE FALSE FALSE

seq(27.39,27.45,by=0.01) %in% seq(27.17,137.74,by=0.01)
[1]  TRUE  TRUE  TRUE  TRUE FALSE  TRUE FALSE

Is this a bug? I am trying to perform operations on a vector of dollar and cent values, and this is making it impossible.

  • 1
    It's not a bug. It's a well known issue with floating point arithmetic. If you need to do something like this, it's better to work with integers and then divide by 100 after the fact. For example: `(seq(2739,2745,by=1)/100) %in% (seq(2717,13774,by=1)/100)` – MrFlick Dec 23 '20 at 04:39
  • I was just reading through the duplicate thread that the moderators linked and groaning at the prospect of using mapply in combination with all.equal for vectorwise comparison. Working with integers instead is a great idea. Thank you! – Christopher Carroll Smith Dec 23 '20 at 04:41
  • 1
    `abs(a - b) < tolerance` from that same answer would be the far easier suggestion for dealing with floating point issues. Assuming that you couldn't avoid the issue using a workaround like MrFlick's integer suggestion. – thelatemail Dec 23 '20 at 05:40

0 Answers0