I am trying to calculate lgamma
using recursion. But it does not work as expected and gives out Nan
and -Inf
. What could be the reason for this?
sum = 0
log_gamma_recursive <- function(n) {
if(n == 1){
return(1)
}else{
sum = sum + log(log_gamma_recursive(n-1))
print(sum)
return(sum)
}
}#log 4 + log 3 + log 2 + log 1
log_gamma_recursive(5)
Three things wrong with the code:
sum
should not be a global variable, because successive "external" calls will return an accumulated valuelog
of the return value to sum
. This will give a series of nested logs:
log 4 + log(log 3 + log(log 2 + log (log 1))))
, which is obviously wronglog(log 1) = log 0
which tends to negative infinity mathematically speaking, but the library may or may not categorize this as a valid inputlog_gamma(1)
is 0, not 1With that in mind, try this:
log_gamma_recursive <- function(n) {
if (n <= 1) {
return (0)
}else{
sum = (log(n-1) + log_gamma_recursive(n-1))
print(sum)
return(sum)
}
}