Math 112: MATLAB Assignment 1

NUMERICAL INTEGRATION Due Date: October 30, 2017

Contents

Sample Program

The sample program below uses the left-endpoint rule, the right-endpoint rule and the trapezoid rule to approximate the definite integral of the function.

$$f(x)=\sin{x}, \, 0<x<\pi.$$

Matlab comments follow the percent sign (%)

a= 0;           % Left endpoint of integral
b= pi;           % Right endpoint
N = 10;         % The number of sub-intervals (|N| must be even for
h=(b-a)/N;
x= a:h:b;      % Creates a vector of N+1 evenly spaced points between |a| and |b|

f=sin(x);         % The function to integrate
Iexact = 2;   % The exact integral

Itrapezoid=0;
Isimpson=0;

for k=1:N  %Note that the vector f has (N+1) elements
    Itrapezoid=Itrapezoid+h*(f(k)+f(k+1))/2;
end;

for k=1:(N/2)
    Isimpson=Isimpson + h/3*(f(2*k-1)+4*f(2*k)+ f(2*k+1));
end

fprintf('              Exact integral = %f.\n', Iexact)
fprintf('   Trapezoidal approximation = %f.\n',Itrapezoid);
fprintf('       Simpson approximation = %f.\n',Isimpson);

fprintf('\n')

fprintf('   Trapezoidal error = %f.\n',abs(Itrapezoid-Iexact));
fprintf('       Simpson error = %f.\n',abs(Isimpson-Iexact));
% Output from this program:
              Exact integral = 2.000000.
   Trapezoidal approximation = 1.983524.
       Simpson approximation = 2.000110.

   Trapezoidal error = 0.016476.
       Simpson error = 0.000110.

New Matlab ideas

Parameters used in this program:

Your assignment

After running the above example, do the following to hand in: (Consult the Matlab TA if you have any questions.)

Approximate the integral of

$$f(x)=e^{2x}, \, -1<x<5$$

Answer the following questions