I'm having trouble trying to optimize a two-parameter exponential distribution, by finding the maximum likelihood function and then using the function optim() in R

enter image description here

log.lik.exp <- function(x, parametros){ 
y <- -1 *(n*log(parametros[1])-parametros[1]*(sum(x)-n*parametros[2]))
mydata <- rand.exp(100, gamma, 1/lambda) 

I'm also trying to use the function persp() to build a 3d plot to get a better look at the maximum values but I keep getting errors.

Thank you in advance, G.

  • 1
    $\begingroup$ It seems this question is mostly about the optim function, and thus might be off topic. But to answer your question, you should check that $\min (x) > \gamma$. If it is not, then you should return $-\infty$. Also, your function technically returns the negative log likelihood. I think it is possibly better to use return the log-likelihood and use the "fnscale" option in optim to perform maximization. $\endgroup$
    – knrumsey
    Dec 1, 2018 at 21:00
  • $\begingroup$ Is your $f(t)$ probability density function (pdf)? I did not get the integral = 1. $\endgroup$
    – user158565
    Dec 1, 2018 at 21:57
  • 1
    $\begingroup$ If $t \leq \gamma$, then the exponential term is positive for all $t \neq \gamma$, and you can see that you'll maximize the likelihood function by making $\gamma$ as large as possible. $\endgroup$
    – jbowman
    Dec 1, 2018 at 22:07

1 Answer 1


As has been pointed out already, the issue is that you are not taking the bounds into consideration. You can fix this by adding an if-statement to your log likelihood function.

log.lik.exp <- function(x, parametros){ 
   if(min(x) < parametros[2]){
   y <- n*log(parametros[1]) - parametros[1]*sum(x-parametros[2])
lambda <- 2
gamma <- 1
mydata <- rand.exp(100, gamma, 1/lambda) 
optim(par=c(1,1), fn=log.lik.exp, x=mydata, control=list(fnscale=-1))$par

I have also added an argument to optim() so that you are maximizing the log-likelihood rather than minimizing the negative log-likelihood. These are of course equivalent, but intuitively I prefer the first.

While we're at it, technically you could get an error if optim proposes a negative value for $\lambda$. This can be fixed in many ways. The simplest of which is to optimize over $\lambda_\star = log(\lambda)$ which can take any real value. Then just back transform, i.e. $\lambda = e^{\lambda_\star}$ at the end.

  • $\begingroup$ I know this comment box says to avoid comments like 'thanks' but I really wanna thank you for your help, I was stuck in this for days and now I can continue! $\endgroup$
    – user228812
    Dec 2, 2018 at 20:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.