10

So I've run into this weird error in R. I have a simple function which returns an error term when comparing real and simulated prices, called hestondifferences().

when I try to find the local minima via:

 res<-optim(fn=hestondifferences, par = c(vT=vT, rho=rho, k=k, sigma=sigma))

I get the error message:

Error in optim(fn = hestondifferences, par = c(vT = vT, rho = rho, k = k, : function cannot be evaluated at initial parameters

What confuses me is that calling the function directly with the initial parameters hestondifferences(vT, rho, k, sigma) returns the correct value.

The function hestondifferences() is written in a way that whenever the simulation is impossible for a certain set of parameters, it returns NA which is in line with what optim() expects.

Andrie
  • 176,377
  • 47
  • 447
  • 496
jcfrei
  • 1,819
  • 4
  • 19
  • 35
  • 1
    Can you show the `hestondifferences` function? – David Robinson Feb 25 '13 at 13:36
  • Damn, just realized my mistake. hestondifferences was expecting four arguments, wheres optim works with just one argument containing a vector. – jcfrei Feb 25 '13 at 13:38
  • 3
    @jcfrei you can answer and accept your own answer. – Paul Hiemstra Feb 25 '13 at 13:40
  • I've spent 1 hour to figure out optim doesn't deal with NAs. I had some in my data and the function kept telling me it couldn't accept such parameters. I would recommend to be extremely carefull with such values as the error message is misleading – Joachim Jun 01 '23 at 15:18

1 Answers1

6

Optim expects functions to just have one argument. All further arguments should hence be passed in a vector. That is: the function must be hestondifferences(c(vT, rho, k, sigma)) instead of hestondifferences(vT, rho, k, sigma). See the documentation:

fn : A function to be minimized (or maximized), with first argument the vector of parameters over which minimization is to take place. It should return a scalar result.

jcfrei
  • 1,819
  • 4
  • 19
  • 35