Search code examples
rstochastic-process

Nonlinear equation involving summations in R


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)

Solution

  • 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.