% Composite Trapezoid Rule and Composite Simpson's Rule % Input: f - integrant function, [a,b] - interval, m - number of nodes % Output: tf - Trapezoidal formula result % sf - Simpson's rule result function[tf,sf,h,h1]=trapez(f,a,b,m) h=(b-a)/m; %Step size for Trapezoidal rule h1=h/2; %Step size for Simpson's rule g=(h/2)*(f(a)+f(b)); s=(h1/3)*(f(a)+f(b)); for k=1:m-1; x=a+k*h; xs1=a+2*k*h1; xs2=a+(2*k-1)*h1; g=g+h*f(x); s=s+(2*h1/3)*f(xs1)+(4*h1/3)*f(xs2); end tf=g; sf=s+(4*h1/3)*f(b-h1); _____________________________________________________________________ clear; a=1; b=6; real=8.1834792077; % Exact inegration value. f=inline('2+sin(2*sqrt(x))'); for j=1:5; m=10+100*(j-1); [tf sf h h1]=trapez(f,a,b,m); A(j,1)=m; A(j,2)=h; A(j,3)=tf; A(j,4)=abs(real-tf); B(j,1)=m; B(j,2)=h1; B(j,3)=sf; B(j,4)=abs(real-sf); end disp('Result from composite Trapezoid rule ') disp(' m h Q[f] E[f] ') disp('----------------------------------------------------------') for k=1:5 disp(sprintf('%2.0f %7.3e %7.15e %7.3e',A(k,1),A(k,2),A(k,3),A(k,4))) end disp(' Result from composite Simpson rule') disp(' m h Q[f] E[f] ') disp('----------------------------------------------------------') for k=1:5 disp(sprintf('%2.0f %7.3e %7.15e %7.3e',B(k,1),B(k,2),B(k,3),B(k,4))) end Result from composite Trapezoid rule m h Q[f] E[f] ---------------------------------------------------------- 10 5.000e-001 8.193854565172531e+000 1.038e-002 110 4.545e-002 8.183563906899268e+000 8.470e-005 210 2.381e-002 8.183502445342256e+000 2.324e-005 310 1.613e-002 8.183489871195299e+000 1.066e-005 410 1.220e-002 8.183485303793596e+000 6.096e-006 Result from composite Simpson rule m h Q[f] E[f] ---------------------------------------------------------- 10 2.500e-001 8.183447496636241e+000 3.171e-005 110 2.273e-002 8.183479205410587e+000 2.289e-009 210 1.190e-002 8.183479207493134e+000 2.069e-010 310 8.065e-003 8.183479207627007e+000 7.299e-011 410 6.098e-003 8.183479207651054e+000 4.895e-011