2013-03-10 134 views
0

如何爲以下代碼設置公差(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 
} 
} 

回答

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 
} 
} 
+0

感謝您的幫助再次。 – 2013-03-10 19:47:08

+0

我們可以將「100」更改爲其他數字嗎? 「tmp」代表什麼? – 2013-03-10 19:51:33

+1

你實際上並不需要'xnew <-xold + 100'這行,而且'tmp <-readline(「繼續?」)'在這裏沒有意義。 – 2013-03-10 19:58:09