虛擬碼
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
#===========================================================
> func(-1.781503813804761e+000) = +0.000000000000000e+000
> func(+2.313837835588586e+000) = +0.000000000000000e+000
> func(+4.947665978216175e+000) = +3.552713678800501e-015
> func(-1.781503813804761e+000) = +0.000000000000000e+000
Julia has no do-while construct. Here is one of several ways to implement do-while behavior.
julia> i = 0
0
julia> while true
println(i)
i += 1
i % 6 == 0 && break
end
===========================================================#
using Printf
#[ -2.00 , -1.00 ] , [ 2.00 , 3.00 ] , [ +4.00 , +5.00 ]
function func(x::Float64)
x2=x*x
x3=x2*x;
return (x3 - 5.48*x2 - 1.4883*x + 20.394828)
end
# funcd(x) = func'(x)
function funcd(x::Float64)
x2=x*x
return (3*x2-10.96*x-1.4883)
end
#-------------------------------------------------------
function NewtonRoot(x0::Float64,eps::Float64) #/* 初點 容許誤差*/
x=x0;
while true
x0=x;
x = x0 - func(x0) / funcd(x0)
(abs(x-x0)<eps) && break
end
return x
end
eps=1.0E-9
max_iterator=100
x0 = -2.0
y0 = NewtonRoot(x0, eps)
s=@sprintf("\n> func(%+.15e) = %+.15e", y0, func(y0))
println(s)
x0 = 2.0
y0 = NewtonRoot(x0, eps)
s=@sprintf("\n> func(%+.15e) = %+.15e", y0, func(y0))
println(s)
x0 = 4.0
y0 = NewtonRoot(x0, eps)
s=@sprintf("\n> func(%+.15e) = %+.15e", y0, func(y0))
println(s)
x0 = -10.0 #// test
y0 = NewtonRoot(x0, eps)
s=@sprintf("\n> func(%+.15e) = %+.15e", y0, func(y0))
println(s)
輸出畫面
沒有留言:
張貼留言