r - 为什么要在 is.wholenumber 中使用这种容差

标签 r

?is.integer 的帮助页面有一个关于一个函数的注释,它会告诉我们一个值是否是一个整数:

is.wholenumber <-
   function(x, tol = .Machine$double.eps^0.5)  abs(x - round(x)) < tol

使用 sqrt(eps) 的参数是什么?作为宽容在这里?此外,是否有充分的理由使用 tol=0 以外的任何其他内容? ?

背景是我对此的回答 question .一些评论者反对这个功能。

我头脑简单的假设:这样做是为了使其接近打印行为(默认为 7 位十进制数字)。例如。:
> 1.000005
[1] 1.000005
> 1.0000000005
[1] 1
> is.wholenumber(1.000005)
[1] FALSE
> is.wholenumber(1.0000000005)
[1] TRUE

虽然它不能完美地工作:
> 1.00000005
[1] 1
> is.wholenumber(1.00000005)
[1] FALSE

下面的评论中有一个更好的论点:sqrt(eps)可能是对浮点运算引起的舍入误差的(粗略)估计。

最佳答案

相比

> is.wholenumber(0.6/0.2, tol=0)
[1] FALSE
> is.wholenumber(0.6/0.2)
[1] TRUE

虽然 3 == 0.6/0.3实际上,在浮点表示中并非如此。

来自 "==" 的帮助文件

For numerical and complex values, remember ‘==’ and ‘!=’ do not allow for the finite representation of fractions, nor for rounding error. Using ‘all.equal’ with ‘identical’ is almost always preferable.


is.wholenumber 的默认容差设置为与 all.equal 相同的数量:
 ## S3 method for class 'numeric'
 all.equal(target, current,
           tolerance = .Machine$double.eps ^ 0.5, scale = NULL,
           ..., check.attributes = TRUE)

这意味着 is.wholenumber 的默认行为相当于
isTRUE(all.equal(0,abs(x - round(x))))

以我们的示例为例
> x <- 0.6/0.2
> x
[1] 3
> round(x)
[1] 3
> x == round(x)
[1] FALSE
> isTRUE(all.equal(0,x-round(x)))
[1] TRUE
> isTRUE(all.equal(0,x-round(x), tol=0))
[1] FALSE

关于r - 为什么要在 is.wholenumber 中使用这种容差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35972288/

相关文章:

r - hclust 函数的聚类列表

list - R:如何使用 R 从 txt 文件中获取信息

r "any of"操作的逻辑条件

r - 如果加载了 ggplot2 包,则在对象上调用 `str` 会出错

r - 获取Rook/Shiny页面用户的私有(private)IP地址

r - R 中用于返回正则表达式中匹配的单词数的语法是什么?

R:计算至少抽到 1 个红色弹珠的概率

r - 使用 nlme::lme 将代码转换为 lme4::lmer

r - 掷骰子数直到达到停止值

r - 如何显示列表的元素