rrecursiongamma

Implenting log-gamma using recursion


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)

Solution

  • Three things wrong with the code:

    1. sum should not be a global variable, because successive "external" calls will return an accumulated value
    2. You add the log of the return value to sum. This will give a series of nested logs:
      • You get log 4 + log(log 3 + log(log 2 + log (log 1)))), which is obviously wrong
      • log(log 1) = log 0 which tends to negative infinity mathematically speaking, but the library may or may not categorize this as a valid input
    3. log_gamma(1) is 0, not 1

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