Martialll
Martialll

Reputation: 51

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?

Upvotes: 4

Views: 16137

Answers (2)

user9798936
user9798936

Reputation:

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`

Upvotes: 3

De Novo
De Novo

Reputation: 7640

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))

Upvotes: 5

Related Questions