Search code examples
ruser-defined-functionsfactorial

lgamma user defined function returns infinite value


This calculates the log of (x-1)! to return the lgamma(x) value of an integer but my function log_gamma works only till x = 171 for x > 171 it returns Inf. How can I solve this problem?

log_gamma <- function(x){
  y <- 1
  if (x < 1)(
    return("Infinity")
  )
  if (x == 1)(
    return(0)
  )
  x <- x-1
  for (i in 1:x){
     y <- y*i
  }
    return(log(y))
}

Solution

  • Your current solution first computes 171! which is a pretty big number. Instead, use the fact that log(a*b) = log(a) + log(b) to compute this as a sum.

    log_gamma <- function(x){
      y <- 1
      if (x < 1)(
        return("Infinity")
      )
      if (x == 1)(
        return(0)
      )
      x <- x-1
      for (i in 1:x){
         y <- y + log(i)
      }
        return(y)
    }
    
    log_gamma(171)
    [1] 707.5731
    log_gamma(172)
    [1] 712.7147
    log_gamma(1000)
    [1] 5906.22