?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/