Mathew Rosales
2008-Oct-15 00:16 UTC
[R] Maximizing a function - optim does not always converge
Hello All,
I¢m kinda new to R language and any help that I can get is greatly appreciated.
Basically, I want to find the values of the two parameters that will maximize
the function and I¢m currently using the optim function to find these values.
My R code works fine but not all the time. Sometimes the solution converges,
sometimes not. Since I¢m planning to do this 5000 times, is there a way where
I can make sure the solution always converge?
size <- 25
n <- rbinom(1, size, 0.6)
data <- log(rlnorm(n, -0.075, sqrt(.15)))
xbar <- mean(data)
sigma2 <- var(data)
s <- n*xbar
tsq <- sum(data^2)
t_init <- xbar-2*sqrt(sigma2/n)
l2 <- function(x){
x1 <- x[1]
x2 <- x[2]
(size - n)*log(1 - exp(t_init - x1 - x2/2)) + n*(t_init -x1 - x2/2) -
(n/2)*log(2*pi) - (n/2)*log(x2) - tsq/(2*x2) + x1*s/x2 - n*(x1^2)/(2*x2)
}
gr.l2 <- function(x){
x1 <- x[1]
x2 <- x[2]
c((size-n)*exp(t_init - x1 -x2/2)/(1-exp(t_init - x1 -x2/2)) - n +
(s/x2) - (n*x1/x2),
(size-n)*exp(t_init - x1 -x2/2)/(1-exp(t_init - x1 -x2/2)) - n/2 -
n/(2*x2) + tsq/(2*x2^2) - x1*s/x2^2 + n*x1^2/(2*x2^2))
}
optim(c(xbar,sigma2), l2, gr.l2, method="BFGS",
control=list(fnscale=-1))
Also, I would like to impose 2 conditions:
1) x2 > 0 and
2) t_init - x1 - x2/2 < 0.
Thanks,
Matt
[[alternative HTML version deleted]]
