Search code examples
rexcelnewtons-method

No sign change found error in R but not excel


Just trying to understand why when I find the root of the following equation in excel I get a value however in R I get the "no sign change found error"

(-exp(-i*x))-x + 1 

i = 1 in this case.

I'm plotting a graph where the value for i is 1:5. I've done this manually on excel and got a value of 0.003 when i = 1, here is the graph for all values of i: image 1

When try to find the root for when i = 1 in R though I get the error.

This is the code I am using to find the root:

func1 <- function(x) {

  (-exp(-1*x))-x+1 
}

root <- uniroot(func1, lower =0.5, upper = 1, extendInt = "yes")
print(root)
print(root$root)

}

Plotting the equation when i = 1 gives the following curve: image 2

Looking at the curve it doesn't seem like f(x) crosses 0 which explains the error, however, I get a value in excel.

Any help on this would be really appreciated

Thanks


Solution

  • This is the best I can offer. It is using a method of derivatives I found at http://rpubs.com/wkmor1/simple-derivatives-in-r. It will allow you to get the roots from newtons method.

    options(scipen = 999)
    f<-function(x) (-exp(-x)-x+1)
    g<-function(x) { }
    body(g)<-D(body(f),"x")
    x <- 19
    y<-vector()
    y[1]<-x
    for(i in 2:500) {
      y<-c(y, y[i-1] - (f(y[i-1])/g(y[i-1])))
      if(y[i]==y[i-1]) break
    }
    y
    

    The output looks like this:

    > y
     [1] 19.000000000000000  0.999999893546867  0.418023257075328  0.194491909332762
     [5]  0.094095681658666  0.046310116577025  0.022976345768161  0.011444180565743
     [9]  0.005711176200954  0.002852869974152  0.001425756748278  0.000712708975595
    [13]  0.000356312158327  0.000178145499021  0.000089070105497  0.000044534390909
    [17]  0.000022267031356  0.000011133470771  0.000005566723944  0.000002783342584
    [21]  0.000001391644148  0.000000695821730  0.000000347990248  0.000000173795172
    [25]  0.000000086916841  0.000000043487300  0.000000023063442  0.000000013435885
    [29] -0.000000003090351 -0.000000003090351
    

    I hope this helps.