Sometimes it is easier to just write it. See below.

On 10-07-30 06:00 AM, r-help-requ...@r-project.org wrote:
Date: Thu, 29 Jul 2010 11:15:05 -0700 (PDT)
From: sammyny<sj...@caa.columbia.edu>
To:r-help@r-project.org
Subject: Re: [R] newton.method
Message-ID:<1280427305687-2306895.p...@n4.nabble.com>
Content-Type: text/plain; charset=us-ascii


newton.method is in package 'animation'.

Thanks Ravi.
BBSolve/BBOptim seems to work very well although I am not familiar with the
optimization methods being used there. Is there a way to specify a tolerance
in the function to get the required precision.

I did something like this to use newton method.
require(animation)
newton.method(f, init=2, tol=10*exp(-8))
But it gives bogus results.

If someone could point me a correct working version of newton method for
finding roots and its usage, that would be helpful.

cheers,

Sam



tfn<-function(x) {
 f = 2.5*exp(-0.5*(2*0.045 - x)) + 2.5*exp(-0.045) + 2.5*exp(-1.5*x) - 100
 return(f)
}
tgr<-function(x) {
 g = 0.5*2.5*exp(-0.5*(2*0.045 - x))  -1.5*2.5*exp(-1.5*x)
 return(g)
}
newt<-function(start, fun, grad) {
    x<-start
    newx<-x+100 # to avoid stopping
    while( 1 != 0) {
       f<-fun(x)
       g<-grad(x)
       newx<-x-f/g
       cat("x, newx, f, g:",x,' ',newx,' ',f,' ',g,"\n")
       if ((100+x) == (100+newx)) return(newx)
       tmp<-readline("continue?")
       x<-newx
    }
}

You can try

   newt(7,tfn, tgr)

   newt(-7,tfn,tgr)

and get both roots quite quickly.

However, I'd probably used uniroot by preference as a general tool. The scripts above are meant for learning purposes.

Best,

John Nash

PS. I did check tgr with numDeriv -- always worth doing.

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to