问题
If I calculate factorial(100)
then I get an answer of [1] 9.332622e+157
but when I try to calculate a larger factorial, say factorial(1000)
I get an answer of [1] Inf
Is there a way to use arbitrary precision when calculating factorials such that I can calculate say factorial(1000000)
?
回答1:
For arbitrary precision you can use either gmp
or Rmpfr
. For specifically factorial gmp
offers factorialZ
and Rmpfr
has factorialMpfr
. So you can run something like below
> Rmpfr::factorialMpfr(200)
1 'mpfr' number of precision 1246 bits
[1] 788657867364790503552363213932185062295135977687173263294742533244359449963403342920304284011984623904177212138919638830257642790242637105061926624952829931113462857270763317237396988943922445621451664240254033291864131227428294853277524242407573903240321257405579568660226031904170324062351700858796178922222789623703897374720000000000000000000000000000000000000000000000000
> gmp::factorialZ(200)
Big Integer ('bigz') :
[1] 788657867364790503552363213932185062295135977687173263294742533244359449963403342920304284011984623904177212138919638830257642790242637105061926624952829931113462857270763317237396988943922445621451664240254033291864131227428294853277524242407573903240321257405579568660226031904170324062351700858796178922222789623703897374720000000000000000000000000000000000000000000000000
HTH
回答2:
I wrote a web scraper; @Khashaa's answer is probably faster, but I went through for proof of concept and to hone my nascent rvest
skills:
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
Another possible advantage is using Wolfram's computing power instead of your own (I don't know how efficient the package options are, I imagine they just use asymptotic approximations so this probably isn't a concern, just thought I'd mention it)
来源:https://stackoverflow.com/questions/32123499/is-there-a-package-or-technique-availabe-for-calculating-large-factorials-in-r