


Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



x 6 3 cos( ) 3 / 2 0
6 3 cos( ) 3 / 2 0 3 / 2 0
x x I x dx x
% --- Numerical Integration: % --- Exploration of the Trapezoid and Simpson Rules clc clear all close all %% --- Define integrand and set limits of integration f = @(x) 6 + 3cos(x) a = 0; b = 3pi/2; x = linspace(a,b); y = f(x); %% --- Exact Integral Int_fun = @(x) 6x + 3sin(x); Iexact = Int_fun(b) - Int_fun(a); Iexact_err = 0; %% --- Trapezoid Rule, n = 1 n = 1; h = (b-a)/n; Itrap1 = (f(a) + f(b))*h/2;
Itrap1_err = abs(Iexact - Itrap1)/Iexact 100; subplot(3,1,1) plot(x,y,[a,b],[f(a),f(b)],'d --','linewidth',2) ylim([0,1.1max(y)]), ylabel('f(x)'), title('Trap, n=1') %% --- Trapezoid Rule, n = 2 n = 2; h = (b-a)/n; Itrap2 = (f(a) + 2f(a+h) + f(b))h/2; Itrap2_err = abs(Iexact - Itrap2)/Iexact 100; subplot(3,1,2) plot(x,y,[a,a+h,b],[f(a),f(a+h),f(b)],'d --','linewidth',2) ylim([0,1.1max(y)]), ylabel('f(x)'), title('Trap, n=2') %% --- Trapezoid Rule, n = 4 n = 4; h = (b-a)/n; Itrap4 = (f(a) + 2f(a+h) + 2f(a+2h) + 2f(a+3h) + f(b))h/2; Itrap4_err = abs(Iexact - Itrap4)/Iexact 100; subplot(3,1,3) plot(x,y,[a,a+h,a+2h,a+3h,b],[f(a),f(a+h),f(a+2h),f(a+3h),f(b)],'d --','linewidth',2) ylim([0,1.1max(y)]), ylabel('f(x)'), title('Trap, n=4') %% --- Simpson's 1/3 Rule, n = 2 n = 2; h = (b-a)/n; Isimp2 = (f(a) + 4f(a+h) + f(b))h/3; Isimp2_err = abs(Iexact - Isimp2)/Iexact 100; %% --- Simpson's 1/3 Rule, n = 4 n = 4; h = (b-a)/n; Isimp4 = (f(a) + 4f(a+h) + 2f(a+2h) + 4f(a+3h) + f(b))h/3; Isimp4_err = abs(Iexact - Isimp4)/Iexact 100; %% --- Simpson's 3/8 Rule, n = 3 n = 3; h = (b-a)/n; Isimp3_8 = (f(a) + 3f(a+h) + 3f(a+2h) + f(b))h*3/8; Isimp3_8_err = abs(Iexact - Isimp3_8)/Iexact *100; %% --- Print table of results fprintf(' a = %4.2f \n b = %4.2f \n\n',a,b) fprintf(' Rule Approx %% Error \n') fprintf(' -------------------------------- \n') fprintf(' Exact %8.3f %8.2f \n',Iexact,Iexact_err) fprintf(' Trap, n=1 %8.3f %8.2f \n',Itrap1,Itrap1_err) fprintf(' Trap, n=2 %8.3f %8.2f \n',Itrap2,Itrap2_err) fprintf(' Trap, n=4 %8.3f %8.2f \n',Itrap4,Itrap4_err) fprintf(' Simp 1/3, n=2 %8.3f %8.2f \n',Isimp2,Isimp2_err) fprintf(' Simp 1/3, n=4 %8.3f %8.2f \n',Isimp4,Isimp4_err) fprintf(' Simp 3/8, n=3 %8.3f %8.2f \n',Isimp3_8,Isimp3_8_err) fprintf(' -------------------------------- \n')
x f(x) n=2, err=5.2% 0 1 2 3 4
x f(x) n=4, err=0.2% 0 1 2 3 4
x f(x) n=6, err=0.0% 0 1 2 3 4
x f(x) n=8, err=0.0%