Reputation: 123
I'm trying to get a function minimum with optim in R, the problem is that the par solution returned by the method is not correct and change if i introduce a different initial point. I will show you some code and the output in getting. What am I missing?
> funx = function(vx) (vx[1] -2)^4 + (vx[1]-2*vx[2])^2 + -10/(vx[1]^2-vx[2])
> optim(c(0,1), funx)
$par
[1] 0.7080021 1.5315815
$value
[1] 18.03898
$counts
function gradient
61 NA
$convergence
[1] 0
$message
NULL
> optim(c(0,3), funx)
$par
[1] 1.271924 1.617791
$value
[1] -4.5036e+16
$counts
function gradient
237 NA
$convergence
[1] 0
$message
NULL
> funx(c(1.271924, 1.617791))
[1] 29566209
Upvotes: 1
Views: 1466
Reputation: 226027
Indeed, this is a rounding problem. If you feed the exact values back to funx()
you get a small (i.e. very negative) value: if you round to six digits you get a large value.
oo <-optim(c(0,3), funx)
funx(oo$par)
## [1] -4.5036e+16
funx(round(oo$par,6))
## [1] 29566209
This is indeed an ill-behaved function, you might need to take this into account when working with it. (I'd also strongly suggest using derivative-based optimization, either calculating the derivatives yourself or using deriv()
.)
Upvotes: 3
Reputation: 374
You may add, for instance, method = "L-BFGS-B" in your optim and define the upper and lower limits of your parameters depending on your definition of the function. It may produce values out of their original intervals.
Upvotes: 0