为牛顿方法设置容差和最大迭代次数

时间:2013-03-10 19:38:55

标签: r max

如何为以下代码设置容差(1e-08)和最大迭代次数(40)?

newton<-function(fun, grad, x_0) { 
 xold<-x_0 
 xnew<-xold+1000 
 while(1! = 0){ 
    f <- fun(xold) 
    g <- grad(xold) 
    xnew <- xold-f/g 
    cat("xold, xnew, f, g:",xold,' ',xnew,' ',f,' ',g,"\n") 
    if ((1000+xold) == (1000+xnew)) return(xnew) 
    tmp<-readline("go on?") 
    xold<-xnew 
 } 
} 

1 个答案:

答案 0 :(得分:3)

newton<-function(fun, grad, x_0,maxiter=40,tol=1e-8) {
 xold<-x_0 
 xnew<-xold+100 # to avoid stopping 
 i<-0 #make counter
 while(i<maxiter){ #do until i=maxiter
    f <- fun(xold) 
    g <- grad(xold) 
    xnew <- xold-f/g 
    cat("xold, xnew, f, g:",xold,' ',xnew,' ',f,' ',g,"\n") 
    #if the absolute difference between old and new value < tol, stop
    if (abs(old-xnew)<tol) return(xnew) 
    tmp<-readline("go on?") 
    xold<-xnew 
    i <- i+1
 } 
}