[英]Factorial function through recursion using R with Rcpp
My basic question is why do the results differ for these four implementations of the factorial function and more specifically why do the functions start to differ for n=13? 我的基本问题是,为什么阶乘函数的这四个实现的结果都不同,更具体地说,为什么在n = 13时函数开始不同?
library(Rcpp)
cppFunction(' int facCpp(int n)
{
if (n==0) return 1;
if (n==1) return 1;
return n*facCpp(n-1);
}
')
cppFunction(' double fac2Cpp(int n)
{
if (n==0) return 1;
if (n==1) return 1;
return n*fac2Cpp(n-1);
}
')
cppFunction(' long int fac3Cpp(long int n)
{
if (n==0) return 1;
if (n==1) return 1;
return n*fac3Cpp(n-1);
}
')
c(factorial(12),prod(1:12),facCpp(12),fac2Cpp(12),fac3Cpp(12))
c(factorial(13),prod(1:13),facCpp(13),fac2Cpp(13),fac3Cpp(13))
c(factorial(20),prod(1:20),facCpp(20),fac2Cpp(20),fac3Cpp(20))
c(factorial(40),prod(1:40),facCpp(40),fac2Cpp(40),fac3Cpp(40))
I realize that the question is perhaps a duplicate since an answers is probably suggested here Rcpp, creating a dataframe with a vector of long long which also shows suggests why the functions start to differ for f(13) 我意识到这个问题可能是重复的,因为在这里可能会建议一个答案Rcpp,创建一个带有long long向量的数据框,这也表明了为什么函数对于f(13)开始有所不同
2^31-1>facCpp(12)
#> [1] TRUE
2^31-1>13*facCpp(12)
#> [1] FALSE
c(factorial(12),prod(1:12),facCpp(12),fac2Cpp(12),fac3Cpp(12))
#>[1] 479001600 479001600 479001600 479001600 479001600
c(factorial(13),prod(1:13),facCpp(13),fac2Cpp(13),fac3Cpp(13))
#> [1] 6227020800 6227020800 1932053504 6227020800 1932053504
c(factorial(20),prod(1:20),facCpp(20),fac2Cpp(20),fac3Cpp(20))
#> [1] 2.432902e+18 2.432902e+18 -2.102133e+09 2.432902e+18 -2.102133e+09
You are essentially doing this wrong. 您本质上是在做错此事。 See the R help page for factorial: 请参阅R帮助页面以了解阶乘:
'factorial(x)' (x! for non-negative integer 'x') is defined to be 'gamma(x+1)' and 'lfactorial' to be 'lgamma(x+1)'. 'factorial(x)'(对于非负整数'x'为x!)定义为'gamma(x + 1)','lfactorial'定义为'lgamma(x + 1)'。
You are not supposed to compute it this way. 您不应以这种方式进行计算。 Why? 为什么? Well look at this: 好看看这个:
R> evalCpp("INT_MAX")
[1] 2147483647
R>
You will hit numerical overflow. 您将遇到数值溢出。 Hence the different algorithm as implemented eg in R's factorial()
function which just does gamma(x+1)
. 因此,例如在R的factorial()
函数中实现的不同算法仅执行gamma(x+1)
。 And you can do that in C++ too: 您也可以在C ++中做到这一点:
R> cppFunction('double myFac(int x) { return(R::gammafn(x+1.0)); }')
R> myFac(4)
[1] 24
R> myFac(12)
[1] 479001600
R> myFac(13)
[1] 6227020800
R> myFac(20)
[1] 2.4329e+18
R> myFac(40)
[1] 8.15915e+47
R>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.