1

Given a function f(x,c,d) of x that also depends on some parameters c and d. I would like to find the zeroes for a cartesian product of certain values c_1,...,c_n and d_1,...,d_m of the parameters, i.e. an x_ij such that f(x_ij,c_i,d_j)=0 for i=1,...,n and j=1,...,m. Although not that crucial I am applying a Newton-Raphson algorithm for the root finding:

newton.raphson <- function(f, a, b, tol = 1e-5, n = 1000){
                  require(numDeriv) # Package for computing f'(x)
                  x0 <- a # Set start value to supplied lower bound
                  k <- n # Initialize for iteration results
                  # Check the upper and lower bounds to see if approximations result in 0
                  fa <- f(a)
                  if (fa == 0.0){
                      return(a)
                   }
                  fb <- f(b)
                  if (fb == 0.0) {
                     return(b)
                  }
                  for (i in 1:n) {
                    dx <- genD(func = f, x = x0)$D[1] # First-order derivative f'(x0)
                    x1 <- x0 - (f(x0) / dx) # Calculate next value x1
                    k[i] <- x1 # Store x1
                    # Once the difference between x0 and x1 becomes sufficiently small, output the results.
                    if (abs(x1 - x0) < tol) {
                          root.approx <- tail(k, n=1)
                          res <- list('root approximation' = root.approx, 'iterations' = k)
                          return(res)
                     }
                     # If Newton-Raphson has not yet reached convergence set x1 as x0 and continue
                     x0 <- x1
                   }
                     print('Too many iterations in method')
                   }

The actual function that I am interest is more complicated, but the following example illustrates my problem.

  test.function <- function(x=1,c=1,d=1){
                   return(c*d-x)
                   }

Then for any given c_i and d_j I can easily calculate the zero by

  newton.raphson(function(x) test.function(x,c=c_i,d=d_j),0,1)[1]

which here is obviously just the product c_i*d_j. Now I tried to define a function that finds for two given vectors (c_1,...,c_n) and (d_1,...,d_m) the zeroes for all combinations. For this, I tried to define

zeroes <- function(ci=1,dj=1){
           x<-newton.raphson(function(x) test.function(x,c=ci,d=dj),0,1)[1]
           return(as.numeric(x))
          }

and then use the outer-function, e.g.

 outer(c(1,2),c(1,2,3),FUN=zeroes)

Unfortunately, this did not work. I got an error message

  Error during wrapup: dims [product 6] do not match the length of object [1]

There might be also a much better solution to my problem. I am happy for any input.

Strickland
  • 590
  • 4
  • 14

0 Answers0