Numeric comparison difficulty in R
I'm trying to compare two numbers in R as a part of a if-statement condition:
(ab) >= 0.5
In this particular instance, a = 0.58 and b = 0.08... and yet (ab) >= 0.5
is false. I'm aware of the dangers of using ==
for exact number comparisons, and this seems related:
(a - b) == 0.5)
is false, while
all.equal((a - b), 0.5)
is true.
The only solution I can think of is to have two conditions: (ab) > 0.5 | all.equal((ab), 0.5)
(ab) > 0.5 | all.equal((ab), 0.5)
. This works, but is that really the only solution? Should I just swear off of the =
family of comparison operators forever?
Edit for clarity: I know that this is a floating point problem. More fundamentally, what I'm asking is: what should I do about it? What's a sensible way to deal with greater-than-or-equal-to comparisons in R, since the >=
can't really be trusted?
I've never been a fan of all.equal
for such things. It seems to me the tolerance works in mysterious ways sometimes. Why not just check for something greater than a tolerance less than 0.05
tol = 1e-5
(a-b) >= (0.05-tol)
In general, without rounding and with just conventional logic I find straight logic better than all.equal
If x == y
then xy == 0
. Perhaps xy
is not exactly 0 so for such cases I use
abs(x-y) <= tol
You have to set tolerance anyway for all.equal
and this is more compact and straightforward than all.equal
.
如果你想经常使用这种方法,你可以创建它作为一个单独的运算符或覆盖原始的> =函数(可能不是一个好主意):
# using a tolerance
epsilon <- 1e-10 # set this as a global setting
`%>=%` <- function(x, y) (x + epsilon > y)
# as a new operator with the original approach
`%>=%` <- function(x, y) (all.equal(x, y)==TRUE | (x > y))
# overwriting R's version (not advised)
`>=` <- function(x, y) (isTRUE(all.equal(x, y)) | (x > y))
> (a-b) >= 0.5
[1] TRUE
> c(1,3,5) >= 2:4
[1] FALSE FALSE TRUE
为了完整起见,我会指出,在某些情况下,您可以简单舍入到小数点后几位(与前面公布的更好的解决方案相比,这是一种蹩脚的解决方案)。
round(0.58 - 0.08, 2) == 0.5
链接地址: http://www.djcxy.com/p/10028.html
上一篇: 切换语句更大
下一篇: R中的数字比较难度