简体   繁体   中英

Factorial with R

I can't calculate the factorial of 365 by using factorial(365) with the R logial, I think the capacity of this logicial don't allow it. How can I do with an other method?

You can use lgamma(x+1) to get the natural log of factorial.

factorial(365)
# [1] Inf
# Warning message:
# In factorial(365) : value out of range in 'gammafn'
lgamma(366)
# 1792.332
# convince yourself that this works:
x <- 2:10
format(factorial(x), scientific = FALSE) == format(exp(lgamma(x + 1)), scientific = FALSE)
[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE

floating point math can get you into trouble at times, but lgamma(366) is accurate for ln(factorial(365))

For large number try to use lfactorial R.base function instead. or lgamma .

factorial(365)
[1] Inf
Warning message:
In factorial(365) : value out of range in 'gammafn'
> lfactorial(365)
[1] 1792.332
> lgamma(365+1)
[1] 1792.332`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM