牛顿法及牛顿下山法求零点

牛顿法
difffun该函数的导函数
a在a附近求零点
ep容忍误差
k迭代次数

function [x_star,k]=MyNewton(fun,difffun,a,ep)


k=1
x_k=a
f_xk=feval(fun,x_k)
fdiff_xk=feval(difffun,x_k)
x_k1=x_k-f_xk/fdiff_xk

    while abs(x_k-x_k1)>ep
        k=k+1
        x_k=x_k1
        f_xk=feval(fun,x_k)
        fdiff_xk=feval(difffun,x_k)
        x_k1=x_k-f_xk/fdiff_xk
    end
    x_star=x_k1

end
牛顿下山法

function [x_star,k]=MyNewton_xiashan(fun,difffun,a,ep)


k=1
x_k=a
f_xk=feval(fun,x_k)
fdiff_xk=feval(difffun,x_k)
x_k1=x_k-f_xk/fdiff_xk
f_xk1=feval(fun,x_k1)
    while abs(x_k-x_k1)>ep
        
        r=1;
        while abs(f_xk1)>abs(f_xk)
            r=r/2
            x_k1=x_k-r*f_xk/fdiff_xk
            f_xk1=feval(fun,x_k1)
            
        end
        k=k+1
        x_k=x_k1
        f_xk=feval(fun,x_k)
        fdiff_xk=feval(difffun,x_k)
        x_k1=x_k-f_xk/fdiff_xk
        f_xk1=feval(fun,x_k1)
    end
    
    
    
    
    x_star=x_k1

end


 
  


你可能感兴趣的:(MATLAB)