检查数字是否为正自然数的最快方法是什么?(在R中)

Tal*_*ili 4 performance r

我很欣赏如何做到这一点,所以我们可以相互比较.

这是一个开始:

is.natural <- function(x)
{
     x>0 && identical(round(x), x)
}
Run Code Online (Sandbox Code Playgroud)

mar*_*cog 5

文件提出了类似的方法,所以我怀疑你会得到任何好转.请记住包含epsilon以考虑精度问题!

is.naturalnumber <-
    function(x, tol = .Machine$double.eps^0.5)  x > tol & abs(x - round(x)) < tol
is.naturalnumber(1) # is TRUE
(x <- seq(1,5, by=0.5) )
is.naturalnumber( x ) #-->  TRUE FALSE TRUE ...
Run Code Online (Sandbox Code Playgroud)