# Log-Likelihood function ¶

Go back

Sometimes, the log-likelihood function is hard to use (mainly when you are not using a computer with the functions already coded for you). The log-likelihood function is something really (yeah, really) easier to use. Everything is working the same, aside from the fact that you are using another function.

Another reason for using the log-likelihood function is that, on average, the result is better than using any other likelihood function.

The log-likelihood function is defined as the sum of the log densities functions.

@ LL(x, \hat{\theta}) = \sum log(f_{\hat{\theta}}(x)) @

## In practice ¶

You will replace prod with sum and add log = TRUE in the density function. You will also need to add a minus before the return. Aside from that, you don't have anything else to change.

# we are chaning the L_bern function
L_bern <- function(theta, x) {
return(-sum(dbinom(x = x, size = 1, prob = theta, log = TRUE)))
}

# this code does not change, working for both
# generating a sample
x <- rbinom(250, 1, prob = 0.8)
# maximum likelihood estimation
first <- sum(x) / length(x)
r <- optim(
fn = L_bern, par = first, x = x,
method = 'L-BFGS-B', lower = 0.0, upper = 1.0
)
# print result