using Printf
function f(x::Float64)
return (0.0000115*(x^2) + 0.000014*(x^1.5)- 0.01962)
end
#define MAX 50 /* maximum iterations */
#define TOL 0.001 /* tolerance */
MAX=50
TOL=0.001
i=1
a=37.0
b=38.0
s=@sprintf(" i\t\ta(i)\t\t\tb(i)\t\t\tp(i)\t\t\tf(p(i))\t\t\th(i)\n")
println(s)
while(i<=MAX)
p=(a+b)/2.0
h=abs((b-a)/2.0)
s=@sprintf("%2d\t\t%9.6lf\t\t%9.6lf\t\t%9.6lf\t\t%9.6lf\t\t%9.6lf", i,a,b,p,f(p),h)
println(s)
if(abs(f(p))==0 || h<TOL)
s=@sprintf("%2d iterations!!!\n",i);
println(s)
S=@sprintf(" The Root=%9.6lf f(%9.6lf)=%9.6lf",p,p,f(p));
println(s)
break
else
if(f(a)*f(p) >0)
a=p
i+=1
else(f(b)*f(p) >0)
b=p
i+=1
end
end
end
s=@sprintf("Bisection Method failed after %d iterations!!!\n",i);
println(s)
輸出畫面
i a(i) b(i) p(i) f(p(i)) h(i) 1 37.000000 38.000000 37.500000 -0.000233 0.500000 2 37.500000 38.000000 37.750000 0.000015 0.250000 3 37.500000 37.750000 37.625000 -0.000109 0.125000 4 37.625000 37.750000 37.687500 -0.000047 0.062500 5 37.687500 37.750000 37.718750 -0.000016 0.031250 6 37.718750 37.750000 37.734375 -0.000000 0.015625 7 37.734375 37.750000 37.742188 0.000008 0.007813 8 37.734375 37.742188 37.738281 0.000004 0.003906 9 37.734375 37.738281 37.736328 0.000002 0.001953 10 37.734375 37.736328 37.735352 0.000001 0.000977 10 iterations!!! 10 iterations!!! Bisection Method failed after 10 iterations!!!
沒有留言:
張貼留言