Optimization of a function in R ( L-BFGS-B needs finite values of ‘fn’)

At some point in the optimization, your function is returning a value greater than .Machine$double.xmax (which is 1.797693e+308 on my machine).

Since your function f1(...) is defined as sum(log(exp(...))), and since log(exp(z)) = z for any z, why not use this:

par1 = c(1, 1, 2, 1.5, 1, 1.5, 1)
x = seq(0, 500, length=100)
f1 = function(par, x){
  sum(-(par[7])*(par[1]*x + par[2]*x^2/2 + 
                           par[3] * (par[4]-x)^3/3+par[6] *(x-par[7])^3/3))
}
result <- optim(par1, f1, x=x, 
                method = "L-BFGS-B", 
                lower = rep(0, length(par1)), upper = rep(Inf,length(par1)),
                control = list(trace = 5,fnscale=-1)) 

result$par
# [1] 2.026284e-01 2.026284e-01 8.290126e+08 0.000000e+00 1.000000e+00 9.995598e+35 2.920267e+27
result$value
# [1] 2.423136e+147

Note that the vector of parameters (par) must be the first argument to f1.

Leave a Comment