虛擬碼
Algorithm NewtonRoot
E0 : 初始化最小誤差 EPS,初始點 xo
E1 : x = x0
E2 : x0 = x - f(x) / f'(x)
E3 : if abs(x-x0) < eps,演算法結束,傳回 x
E4 : goto E1
End Algorithm
============================================
MAX=100
TOL=0.001
function fx(x::Float64)
return (cos(x)-x)
end
function ffx(x::Float64) # fx =(cos(x)-x) 的微分值
return (-sin(x)-1)
end
i=1
x0=1.0
println(" i Root of f(x)")
while(i<=MAX)
x=x0-fx(x0)/ffx(x0);
s=@sprintf("%2d %10.7lf",i,x0);
println(s)
if(abs(x-x0) <TOL)
s=@sprintf("Root=%10.7lf x-x0=%10.7lf",x,abs(x-x0));
println(s)
break
end
i+=1
x0=x
end
println()
s=@sprintf("Newton-Raphson Method failed after %2d iterations!!!\n",i)
println(s)
輸出畫面
i Root of f(x)
1 1.0000000
2 0.7503639
3 0.7391129
Root= 0.7390851 x-x0= 0.0000278
Newton-Raphson Method failed after 3 iterations!!!
沒有留言:
張貼留言