检查数字是否为整数 [英] Check if the number is integer

查看:236
本文介绍了检查数字是否为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很惊讶地发现R没有方便的功能来检查数字是否为整数。

I was surprised to learn that R doesn't come with a handy function to check if the number is integer.

is.integer(66) # FALSE

帮助文件警告


is.integer(x)不测试 x
是否包含整数!为此,
使用 round ,如函数
is.wholenumber(x)在示例中。

is.integer(x) does not test if x contains integer numbers! For that, use round, as in the function is.wholenumber(x) in the examples.

该示例将此自定义函数作为解决方法

The example has this custom function as a "workaround"

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

如果我要写一个检查整数的函数,假设我没有读过上面的注释,我会编写一个函数,它会像

If I would have to write a function to check for integers, assuming I hadn't read the above comments, I would write a function that would go something along the lines of

check.integer <- function(x) {
    x == round(x)
}

我的方法在哪里失败?如果你穿着我的假想鞋,你的工作会是什么?

Where would my approach fail? What would be your work around if you were in my hypothetical shoes?

推荐答案

另一个选择是检查小数部分:

Another alternative is to check the fractional part:

x%%1==0,

或,

min(abs(c(x%%1, x%%1-1))) < tol,

如果你想在一定的公差范围内检查。

if you want to check within a certain tolerance.

这篇关于检查数字是否为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆