?is.integer
的帮助页面中有一个关于函数的注释,该函数将告诉我们值是否为整数:
is.wholenumber <-
function(x, tol = .Machine$double.eps^0.5) abs(x - round(x)) < tol
在这里使用sqrt(eps)
作为容忍的理由是什么?另外,是否有充分的理由使用除tol=0
以外的任何其他内容?
背景是我对此question的回答。一些评论者反对这一功能。
我的简单假设:这样做是为了使其在行为中接近打印(默认值为7位小数)。 E.g:
> 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)
可能是由浮点运算引起的舍入误差的(粗略)估计。
答案 0 :(得分:1)
比较
> is.wholenumber(0.6/0.2, tol=0)
[1] FALSE
> is.wholenumber(0.6/0.2)
[1] TRUE
虽然3 == 0.6/0.3
完全在现实中,但在浮点表示中并非如此。
来自"=="
对于数值和复数值,请记住'=='和'!='不要 允许分数的有限表示,也不允许舍入 错误。使用'all.equal'和'same'几乎总是如此 优选的。
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