0

I am having the hardest time trying to implement this equation into a nonlinear solver in R. I am trying both the nleqslv and BB packages but so far getting nothing but errors. I have searched and read documentation until my eyes have bled, but I cannot wrap my brain around it. The equation itself works like this:

The Equation

s2 * sum(price^(2*x+2)) - s2.bar * sum(price^(2*x)) = 0

Where s2, s2.bar and price are known vectors of equal length.

The last attempt I tried in BB was this:

gamma = function(x){
        n = len(x)
        f = numeric(n)
        f[n] = s2*sum(price^(2*x[n]+2)) - s2.bar*sum(price^(2*x[n]))
        f
      }

g0 = rnorm(length(price))
results = BBsolve(par=g0, fn=gamma)
Cettt
  • 11,460
  • 7
  • 35
  • 58
Lompoc42
  • 55
  • 5
  • f[n] is one element of a vector but you're trying to assign to it an entire vector of length equal to length(s2). Do you mean to be using s2[n] and s2.bar[n] instead of s2 and s2.bar? price doesn't cause a problem because you're summing over the whole vector after taking the exponent. – Jon Apr 13 '17 at 20:55
  • Let me try that again: I am probably going all wrong from the start then. The actual equation I'm trying to solve is this: http://i1330.photobucket.com/albums/w561/lompoc421/CodeCogsEqn%201_zpsrwocvotk.gif – Lompoc42 Apr 13 '17 at 21:26

1 Answers1

0

From you description of the various parts used in the function you seem to have muddled up the formula.

Your function gamma should most probably be written as

gamma <- function(x){
    f <- s2*sum(price^(2*x+2)) - s2.bar*sum(price^(2*x))
    f
}

s2, price and s2.bar are vectors from your description so the formula you gave will return a vector.

Since you have not given any data we cannot test. I have tried testing with randomly generated values for s2, price, s2.bar. Sometimes one gets a solution with both nleqslv and BB but not always.

In the case of package nleqslv the default method will not always work. Since the package has different methods you should use the function testnslv from the package to see if any of the provided methods does find a solution.

Bhas
  • 1,844
  • 1
  • 11
  • 9
  • I can't believe it ended up being as easy as this. This seems to work, though not always, but that's another issue entirely. Thank you! – Lompoc42 Apr 14 '17 at 12:02
  • And do not forget to test the `nleqslv` and `BBsolve` termination codes to check if a solution has been found. And give an upvote? – Bhas Apr 14 '17 at 13:48
  • Yeah, I had to write a small testing while loop to make sure that it threw back solutions which converged. Hopefully I'm on the right track. Tried to upvote but it won't let me without at least 15 reputation points. – Lompoc42 Apr 14 '17 at 14:07