虛擬碼
Algorithm SecantRoot
E0 : 初始化最小誤差 EPS,初始點 xo, x1
E1 : 算 y0 = f(x0), y1 = f(x1)
E2 : x2 = x1 - y1*(x1-x0) / (y1-y0), delta = x2-x1
E3 : x0 = x1, x1 = x2, y0=y1, y1=f(x1)
E4 : if abs(delta) < eps 或 abs(y1-y0) < eps,演算法結束,傳回 x2
E5 : goto E2
End Algorithm
using Printf
#========================================================================
/*----------------------------------------------------------------*\
|
| E0 : 初始化最小誤差EPS,初始點x0, x1
| E1 : y0 = f(x0) , y1 = f(x1)
| E2 : x2 = x1 - y1 * (x1 - x0) / (y1 - y0), delta = x2 - x1
| E3 : x0 = x1, x1 = x2, y0 = y1, y1=f(x1)
| E4 : if abs(delta) or abs(y1-y0), 演算法結束, 傳回x2
| E5 : goto E2
|
\*----------------------------------------------------------------*/
========================================================================#
MAX=50
TOL=0.00001
function fx(x::Float64)
return (exp(x)+1/(2^x)+2*cos(x)-6)
end
i=2
x0=1.8
x1=2.0
q0=fx(x0);
q1=fx(x1);
s=@sprintf("i xi f(x)")
println(s)
s=@sprintf("%-2d %10.6lf %10.6lf",0,x0,q0)
println(s)
s=@sprintf("%-2d %10.6lf %10.6lf",1,x1,q1)
println(s)
while(i<=MAX)
x=x1-q1*(x1-x0)/(q1-q0);
s=@sprintf("%-2d %10.6lf %10.6lf",i,x,fx(x))
println(s)
if(abs(x-x1) < TOL)
s=@sprintf("The Root=%10.6lf f(%10.6lf)=%10.6lf",x,x,fx(x))
println(s)
break
else
i+=1
x0=x1
q0=q1
x1=x
q1=fx(x)
end
end
if(i>MAX)
s=@printf("Secant Method faileds!!!\n")
println(s)
end
輸出畫面
i xi f(x)
0 1.800000 -0.117582
1 2.000000 0.806762
2 1.825441 -0.016116
3 1.828860 -0.002147
4 1.829385 0.000007
5 1.829384 -0.000000
The Root= 1.829384 f( 1.829384)= -0.000000
沒有留言:
張貼留言