# L-25 MCS 471 Wed 19 Oct 2022 : comptrap.jl using Printf """ Applies the composite trapezoidal rule to approximate the integral of the function f over the interval [a,b], using n subintervals. Example: t = comptrap(cos,0,pi/2,100) """ function comptrap(f::Function,a::Float64,b::Float64,n::Int64) h = (b-a)/n t = (f(a) + f(b))/2 for i = 1:n-1 t = t + f(a+i*h) end t = t*h return t end """ Applies the composite trapezoidal rule to the area under the unit circle. """ function main() f(x) = sqrt(1 - x^2) exact = pi/4 N = 1 for i=1:21 t = comptrap(f,0.0,1.0,N) strnbr = @sprintf("%7d", N) strval = @sprintf("%.16e", t) strerr = @sprintf("%.2e", abs(t-exact)) println(" $strnbr $strval $strerr") N = 2*N end end main()