0

I am trying to make a function of the type y = ax + b that changes its arguments depending on the values taken by the "x" values. I therefore use the operator %in% to detect whether "x" is in the required range of abscissa. There is one of those cases, which is here problematic, where the equation must work for abscissas ranging from negative (-1.02) to positive (0.08) values. I use :

as.character(0.07) %in% seq(from = -1.02, to = 0.08, by = 0.01)
FALSE

Unexpectedly, this gives me a FALSE result. When I try another x value, with a more restricted range of negative values, it now becomes TRUE :

as.character(0.07) %in% seq(from = -0.20, to = 0.08, by = 0.01)
TRUE

The same occurs whether I try for negative or positive "x" values. I have absolutely no clue for why this is happening. Worth mentioning I keep with the version "2022.07.2 Build 576" compatible with my windows 8.1 version.

joran
  • 169,992
  • 32
  • 429
  • 468
  • 1
    If you coerce the output from `seq()` to character and look at the results, you'll see where this is going wrong, e.g. `as.character(seq(from = -1.02, to = 0.08, by = 0.01))`. – joran Mar 08 '23 at 19:52
  • 1
    I believe this is covered in The R Inferno section of floating point math (edit actually the first paragraph of chapter 1 https://www.burns-stat.com/pages/Tutor/R_inferno.pdf) – Bill O'Brien Mar 08 '23 at 19:53
  • Also, the very end of the top answer at the duplicate has an explicit solution spelled out for `%in%` in particular. – joran Mar 08 '23 at 19:54
  • As @BillO'Brien points out. Checkout the result of `as.character(seq(from = -1.02, to = 0.08, by = 0.01))` – SmokeyShakers Mar 08 '23 at 19:55
  • Thank you all for your replies! I actually had no idea of floating points... But this seems to be what happened. I found a tricky solution which could help anybody faces the same problem... : as.character(0.07) %in% seq(from = -1.02, to = 0.08, by = 0.01) becomes: !identical(grep(as.numeric(format(round(0.07,2), nsmall = 2)), as.numeric(format(round(seq(from = -1.02, to = 0.08, by = 0.01), 2), nsmall = 2))), integer(0)) ==TRUE – DPEaleo Mar 10 '23 at 11:40

0 Answers0