数值比较难度 [英] Numeric comparison difficulty in R

查看:152
本文介绍了数值比较难度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图比较R中的两个数字作为if语句条件的一部分:

I'm trying to compare two numbers in R as a part of a if-statement condition:

(ab)> = 0.5

在这个特定实例中,a = 0.58和b = 0.08 ...还有 ; = 0.5 为false。我知道使用 == 进行确切的数字比较的危险,这似乎相关:

In this particular instance, a = 0.58 and b = 0.08... and yet (a-b) >= 0.5 is false. I'm aware of the dangers of using == for exact number comparisons, and this seems related:

code>(a - b)== 0.5)为false,而

(a - b) == 0.5) is false, while

all.equal (a-b),0.5)是真的。

我可以想到的唯一解决方案是有两个条件:(ab)> 0.5 | all.equal((a-b),0.5)。这工作,但是这真的是唯一的解决方案吗?我应该只是发出 = 家族的比较运算符吗?

The only solution I can think of is to have two conditions: (a-b) > 0.5 | all.equal((a-b), 0.5). This works, but is that really the only solution? Should I just swear off of the = family of comparison operators forever?

/ strong>我知道这是一个浮点问题。更基本的是,我要问的是:我该怎么办?因为> = 不能真正被信任,所以在R中处理大于或等于比较是一个明智的方法吗?

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?

推荐答案

我从来不是这样的事情的 all.equal 的粉丝。在我看来,容忍有时以神秘的方式工作。为什么不检查大于0.05以下的公差

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)

一般来说,我发现直逻辑比all.equal更好。

In general, without rounding and with just conventional logic I find straight logic better than all.equal

如果 x == y 那么 xy == 0 。也许 xy 不完全是0,所以对于这种情况,我使用

If x == y then x-y == 0. Perhaps x-y is not exactly 0 so for such cases I use

abs(x-y) <= tol

您必须为 all .equal ,这比 all.equal 更紧凑和直接。

You have to set tolerance anyway for all.equal and this is more compact and straightforward than all.equal.

这篇关于数值比较难度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆