#================================================
* ex4-1.jl based on Trapezoidol Rule is
* used for computing definite integral with
* domain [a,b] with n even-grids.
*
梯形法 T'= (h/2) [ f(a) + f(b) + 2 sigma i=1 to n-1 f(xi)]
=================================================#
using Printf
function f(x::Float64) #// 欲微分函數
return exp(x)
end
result=0.0
n=10
a=0.0
b=1.0
h=(b-a)/n
x=a
for i=1:n-1
x=x+h;
s=@sprintf("x=%0.1f ---- f(x)=%0.4f",x,f(abs(x)))
println(s)
result=result+f(abs(x))
end
tn=(h/2.0)*( f(abs(a)) + f(abs(b)) + 2.0*result )
println("\nf(x)=exp(x) a=0.0 ,b=1.0 n=10 ")
s=@sprintf("T%d=%10.6lf\n",n,tn)
println(s)
s=@sprintf("梯形積分與實際值的誤差值=%0.5f",abs(tn-(f(1.0)-f(0.0))))
println(s)
ET= (f(b)* (b-a)^3) / (12*n^2)
s=@sprintf("梯形法的誤差範圍= %0.5f",ET)
println(s)
輸出畫面
x=0.1 ---- f(x)=1.1052
x=0.2 ---- f(x)=1.2214
x=0.3 ---- f(x)=1.3499
x=0.4 ---- f(x)=1.4918
x=0.5 ---- f(x)=1.6487
x=0.6 ---- f(x)=1.8221
x=0.7 ---- f(x)=2.0138
x=0.8 ---- f(x)=2.2255
x=0.9 ---- f(x)=2.4596
f(x)=exp(x) a=0.0 ,b=1.0 n=10
T10= 1.719713
梯形積分與實際值的誤差值=0.00143
梯形法的誤差範圍= 0.00227
沒有留言:
張貼留言