tags:

views:

44

answers:

1

Hi, Is this method broken in R? I am using it to find roots of the following function: f(x) = 2.5*exp(-0.5*(2*0.045 - x)) + 2.5*exp(-0.045) + 2.5*exp(-1.5*x) - 100

It is giving an answer of -38.4762403 which is not even close (f(x) = 2.903809e+25 for x=-38.4762403). The answer should be around 0.01-0.1. This function should converge..

Even for a simple function like f(x) = exp(-x) * x, it gives answer as 8.89210984 for which f(x) = 0.001222392 and I set tolerance to 10^-12..

Also, is there a non graphical version of newton method? I looked at nleqslv but have no idea how to use it..

Thanks for your help.

+1  A: 

R has a number of root finders, such as uniroot and polyroot. For more complicated problems you can use optimisation functions such as optim, optimize or nlminb. Here is an example of solving this problem with uniroot.

## define the function
f <- function(x){                                                                                                                                            
  2.5*exp(-0.5*(2*0.045 - x)) + 2.5*exp(-0.045) + 2.5*exp(-1.5*x) - 100                                                                                      
}                                                                                                                                                            

## plot the function 
y <- seq(-20,20,0.1) 
plot(y,f(y),ylim = c(-100,100),xlim=c(-20,20))

## find the roots
uniroot(f,c(-5,0))
uniroot(f,c(0,10))
nullglob
That is so cool. This would sure come handy back in high school!
Roman Luštrik
Thanks. It looks like it uses something similar to bisection method. Your call should be uniroot(f,c(-5,5)) for this to work. I am still searching for a working version of newton's method :(