可以在 R 中的递归阶乘中使用的最大 n

the largest n that you can use in recursion factorial in R

我有一个递归阶乘

recursive.factorial <- function(x) {
    if (x == 0)    return (1)
    else           return (x * recursive.factorial(x-1))
}

只是好奇我的 recursive.factorial v.s R 中的 build-int factorial() 函数中最大的 x 是什么?有没有办法检查一下

计算机数值的位跨度似乎比 "computer memory" 更有可能成为问题,我假设您指的是 RAM 地址 space。在 R(以及使用通常的 IEEE 标准的任何软件包)中无需近似即可表示的整数的最大值是 2^53 - 1。还有其他包(其中一些作为 R 包提供)可以支持任意精度数字。 ?Recall 函数是一种更稳定的递归方法,尽管它在 R 中没有优化。integer.max 设置为 2 个字节可获得的精度:

 2^32-1
[1] 4294967295

最近引入的 "long integers" 达到浮点数尾数的极限 "doubles"。

> 2^53-1
[1] 9.007199e+15
> print( 2^53-1, digits=18)
[1] 9007199254740991

因此,一旦您获得大于该限制的 factorial(n) 值,您只会得到一个近似值,而当您超过 "double" 数值的指数限制时,您会得到"Inf"。我的factorial版本好像和你的一样断点:

> fact <- function(n)
+    if(n==0) { 1} else{ (n) *Recall(n-1)}
> fact (170)
[1] 7.257416e+306
> fact (171)
[1] Inf

这是另一种计算阶乘的方法:

> exp( sum(log(1:15)))
[1] 1.307674e+12
> factorial(15)
[1] 1.307674e+12

"Stirling's approximation" 通常用于加速阶乘的计算。要获得更准确的值,您可以安装 gmpRmpfr 软件包。