Math 112: MATLAB Assignment 1
NUMERICAL INTEGRATION Due Date: MARCH 9, 2018
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.
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
- A For Loop. Repeat the code between 'for' and 'end' once for each number between 1 and N
- the fprintf statement. This is a formatted printing statement, which uses almost identical syntax to the C programming language. It is used here to format the output for display. You should be able to use this part of the program without modifying it.
Parameters used in this program:
- a,b: the limits of integration
- x: the variable of integration
- f: the integrand
- N: the number of sub-intervals
- h: the width of each sub-interval
- IT: the trapezoidal approximation
- IS: the Simpson approximation
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
Answer the following questions
- Run the code with N=16, N=32, and N=64.
- For each approximation, when does the result agree with the exact value of the integral to 4 digits?
- How much better is the Simpson's rule than the trapezoidal rule? Explain this result using the theory given in the textbook and in lecture. Be quantitative. Calculate the ratios between the errors each time the number of points is doubled.