0

I just encounter a very weird issue. Following is the code

a <- 90.8
b <- 90.6
a - b == 0.2

returns FALSE

Any ideas???

Arthur
  • 398
  • 6
  • 20
  • 2
    because of floating point. You can check `print(a-b, digits=20)# [1] 0.20000000000000284` – akrun Oct 05 '17 at 13:57
  • Yeah, that's true. So how can I fix that? I need to write an if condition on the difference. – Arthur Oct 05 '17 at 13:59
  • Well, what condition do you need? Presumably, it is not that the difference is exactly 0.2. – G5W Oct 05 '17 at 14:01
  • 2
    Use `all.equal`. – Taylor H Oct 05 '17 at 14:02
  • What if I want to use inequality? For example, `90.8 - 90.6 <= 0.2`, which will give `FALSE` – Arthur Oct 05 '17 at 14:05
  • 1
    `is.less <- function(x, y, tol = .Machine$double.eps^0.5) x - y < tol; is.less(90.8 - 90.6, 0.2)` returns `TRUE`. Same for `<=` or `>`. If you want equality use `abs(x - y) < tol`. – Rui Barradas Oct 05 '17 at 14:11
  • @RuiBarradas Thank you! – Arthur Oct 05 '17 at 14:14
  • 1
    `isTRUE(all.equal(a - b, 0.2))` is what you should be using – rawr Oct 05 '17 at 14:26
  • @rawr That's the standard way but the reason why the function in my comment is that `all.equal` is not vectorized and sometimes we need a logical vector. Note that I use the same default tolerance as `all.equal`. – Rui Barradas Oct 05 '17 at 17:37

0 Answers0