felipe gateño
felipe gateño

Reputation: 13

Difference between log likelihood by hand and logLike function

I'm trying to compare the value of the log likelihood function given by the logLik function and the value calculate by hand for a Gamma distribution. The value given by the logLik function is:

require(fitdistrplus)

x = rgamma(50,shape = 2, scale = 10)
Gamma_fitdist = fitdist(x,"gamma")
logLik(Gamma_fitdistr)
-189.4192

and for the loglikelihood function "by hand" is:

gmll <- function(scale,shape,datta){
  a <- scale
  b <- shape
  n <- length(datta)
  sumd <- sum(datta)
  sumlogd <- sum(log(datta))
  gmll <- n*a*log(b) + n*lgamma(a) + sumd/b - (a-1)*sumlogd
  gmll
} 

gmll(scale = 10, shape = 2, datta = x)
-246.6081

Why logLik function give me a different value? Thanks!

Upvotes: 1

Views: 205

Answers (1)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84659

You've interverted scale and shape and there's a couple of sign errors in your code.

library(fitdistrplus)

set.seed(666)
x = rgamma(50, shape = 2, scale = 4)

Gamma_fitdist = fitdist(x,"gamma")
logLik(Gamma_fitdist)
# -150.3687

gmll <- function(scale,shape,datta){
  a <- shape
  b <- scale
  n <- length(datta)
  sumd <- sum(datta)
  sumlogd <- sum(log(datta))
  -n*a*log(b) - n*lgamma(a) - sumd/b + (a-1)*sumlogd
} 

rate <- Gamma_fitdist$estimate[["rate"]]
shape <- Gamma_fitdist$estimate[["shape"]]
gmll(scale = 1/rate, shape = shape, datta = x)
# -150.3687

Upvotes: 2

Related Questions