如果我计算factorial(100)
,那么我会得到[1] 9.332622e+157
的答案,但当我尝试计算更大的阶乘时,请说factorial(1000)
我会得到[1] Inf
的答案
有没有办法在计算阶乘时使用任意精度,以便我可以计算说factorial(1000000)
?
答案 0 :(得分:7)
对于任意精度,您可以使用gmp
或Rmpfr
。对于具体的因子gmp
商品factorialZ
和Rmpfr
商品factorialMpfr
。所以你可以运行类似下面的内容
> Rmpfr::factorialMpfr(200)
1 'mpfr' number of precision 1246 bits
[1] 788657867364790503552363213932185062295135977687173263294742533244359449963403342920304284011984623904177212138919638830257642790242637105061926624952829931113462857270763317237396988943922445621451664240254033291864131227428294853277524242407573903240321257405579568660226031904170324062351700858796178922222789623703897374720000000000000000000000000000000000000000000000000
> gmp::factorialZ(200)
Big Integer ('bigz') :
[1] 788657867364790503552363213932185062295135977687173263294742533244359449963403342920304284011984623904177212138919638830257642790242637105061926624952829931113462857270763317237396988943922445621451664240254033291864131227428294853277524242407573903240321257405579568660226031904170324062351700858796178922222789623703897374720000000000000000000000000000000000000000000000000
HTH
答案 1 :(得分:3)
我写了一个网络刮刀; @Khashaa的答案可能更快,但我经历了概念验证并磨练我的新生rvest
技能:
library(rvest)
Factorial<-function(n){
x<-strsplit(strsplit((html(paste0(
#%21 is URL speak for !
"http://www.wolframalpha.com/input/?i=",n,"%21")) %>%
#to understand this part, I recommend going to the site
# and doing "Inspect Element" on the decimal representation
html_nodes("area") %>% html_attr("href")),
split="[=&]")[[1]][2],split="\\+")[[1]]
cat(paste0(substr(x[1],1,8), #8 here can be changed to the precision you'd like;
# could also make it match printing options...
"e+",gsub(".*E","",x[3])))
}
> Factorial(10000)
2.846259e+35659
另一个可能的优势是使用Wolfram的计算能力而不是你自己(我不知道包选项的效率如何,我想他们只是使用渐近近似,所以这可能不是关注,只是以为我提到了它)