Why is uniroot.all throwing unused variable error when root function has multiple arguments?

154 Views Asked by At

Once in a blue moon I need to use the lovely uniroot.all function from the rootSolve package to find the root(s) of a function with multiple arguments. Every time I do this I run into a bunch of snags which I eventually resolve, but then forget how I resolved them the next time around. So, this time I am registering the snags here so that hopefully next time I can just look here and see how to resolve them quickly.

Here is some example code:

testFn <- function(x, a, b, thresh){
  f <- a * x^2 - b
  slack <- f - thresh
  return(slack)
}

a <- 1
b <- 2
thresh <- 0
xGuess <- 1
testFn(xGuess, a, b, thresh)
interval <- c(0, 2)
testRoot <- rootSolve::uniroot.all(testFn,
                                   interval = interval,
                                   lower = min(interval),
                                   upper = max(interval),
                                   x = xGuess,
                                   a = a,
                                   b = b,
                                   thresh = thresh)

This should give a root of x equals square root of 2, but instead throws the following error:

Error in f(xseq, ...) : unused argument (xseq)

I think the problem has something to do with how I pass extra parameters like a, b, thresh to testFn()

1

There are 1 best solutions below

0
On

Your problem is including x = xGuess:

library(rootSolve)
uniroot.all(testFn,
            interval = interval,
            lower = min(interval),
            upper = max(interval),
            #x = xGuess,
            a = a,
            b = b,
            thresh = thresh)
## [1] 1.41418

If you type uniroot.all (without the () ) you can see the code. It calls f(xreg, ...), which works if the first argument is x and only the extra arguments (a, b, and thresh in your case) are specified.