all.equal()的容差参数如何工作?

woo*_*ert 12 r

有人可以向我解释一下公差参数all.equal吗?

手册说(?all.equal):

tolerance:numeric≥0.不考虑小于容差的差异.

scale = NULL(默认值)的数值比较是通过首先计算两个数值向量的平均绝对差值来完成的.如果这小于容差或不是有限的,则使用绝对差异,否则相对差异按平均绝对差异缩放.

例:

all.equal(0.3, 0.26, tolerance=0.1)
Run Code Online (Sandbox Code Playgroud)

回报 Mean relative difference: 0.1333333

为什么这里返回平均相对差异?两个数值向量的平均绝对差值是否小于容差?

0.3 - 0.26 = 0.04 < 0.1
Run Code Online (Sandbox Code Playgroud)

谢谢!

Aru*_*run 13

如果target大于tolerance,它似乎检查relative error <= tolerance.那就是abs(current-target)/target <= tolerance:

all.equal(target, current, tolerance)
Run Code Online (Sandbox Code Playgroud)

例如:

all.equal(3, 6, tolerance = 1)
# TRUE --> abs(6-3)/3 <= 1
Run Code Online (Sandbox Code Playgroud)

相反,如果target小于tolerance,则all.equal使用mean absolute difference.

all.equal(0.01, 4, tolerance = 0.01)
# [1] "Mean absolute difference: 3.99"

all.equal(0.01, 4, tolerance = 0.00999)
# [1] "Mean relative difference: 399"

all.equal(4, 0.01, tolerance = 0.01)
# [1] "Mean relative difference: 0.9975"
Run Code Online (Sandbox Code Playgroud)

但是,这不是文档所述的内容.为了进一步了解为什么会发生这种情况,让我们来看看相关的代码片段all.equal.numeric:

# take the example: all.equal(target=0.01, current=4, tolerance=0.01)
cplx <- is.complex(target) # FALSE
out <- is.na(target) # FALSE
out <- out | target == current # FALSE

target <- target[!out] # = target (0.01)
current <- current[!out] # = current (4)

xy <- mean((if(cplx) Mod else abs)(target - current)) # else part is run = 3.99

# scale is by default NULL
what <- if (is.null(scale)) {
    xn <- mean(abs(target)) # 0.01
    if (is.finite(xn) && xn > tolerance) { # No, xn = tolerance
        xy <- xy/xn
        "relative"
    }
    else "absolute" # this is computed for this example
}
else {
    xy <- xy/scale
    "scaled"
}
Run Code Online (Sandbox Code Playgroud)

在上面的代码中检查的所有内容(仅显示来自OP的示例的必要部分)是:从和中删除任何NA和(targetcurrent)的相等值.然后计算为的平均绝对差和.但是,在决定是否将是或取决于部件.这里没有检查任何条件.这取决于只有在这.targetcurrentxytargetcurrentrelativeabsolutewhatxyxnmean(abs(target))

因此,总之,OP粘贴的部分(为方便起见粘贴在这里):

如果(意味着,平均绝对差值)小于容差或不是有限的,则使用绝对差异,否则相对差异由平均绝对差异缩放.

似乎错误/误导.