newton<-function(x0, eps) { repeat { x1<-x0 - fun(x0)/derf(x0) if(abs(x0 - x1) < eps) break x0<-x1 } x1 } fun<-function(x){ x * exp(-x) - 0.2 } derf=function(x) { (1-x)*exp(-x) } x<-seq(-2, 2, , 20) fun(x) x<-seq(-1, 4, , 20) plot(x, fun(x)) abline(h=0, col=2) newton(0.0, .000001) newton(2.0, .000001) newton<-function(x0, eps) { k<-0 repeat { k<-k + 1 x1<-x0 - fun(x0)/derf(x0) if(abs(x0 - x1)< eps) break x0<-x1 cat("Iteration No: ", k, "Current iterate = ",x1 , fill=T) } x1 } #> source("newton.s") # newton(0.0, .000001) newton2<- function(fun, derf, x0, eps){ k<- 0 repeat { k<- k + 1 x1<- x0 - fun(x0)/derf(x0) if(abs(x0 - x1)< eps) break x0<- x1 cat("Iteration No: ", k, "Current iterate = ",x1 , fill=T) } x1 } myfun<- function(x){ x * exp(- x) - 0.2 } deriv<- function(x){ (1 - x) * exp(- x) }