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

问题描述

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

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

(a-b) >= 0.5

在这个特定的例子中,a = 0.58 和 b = 0.08...但 (a-b) >= 0.5 是假的.我知道使用 == 进行精确数字比较的危险,这似乎是相关的:

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:

(a - b) == 0.5) 是假的,而

all.equal((a - b), 0.5) 为真.

我能想到的唯一解决方案是有两个条件:(a-b) >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?

为清楚起见进行我知道这是一个浮点问题.更根本的是,我要问的是:我该怎么办?在 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 那么x-y == 0.也许 x-y 不完全是 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.

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

07-23 06:53