Math 112 Honors: MATLAB Assignment 1
NUMERICAL INTEGRATION Due Date: March 3, 2011
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; b= 1; N = 10; h=(b-a)/N; x=[a:h:b]; %creates a vector of n+1 evenly spaced points f=x.^2; IL=0; IR=0; IT=0; for k=1:N; %Note that the vector f has (N+1) elements IL=IL+f(k); IR=IR+f(k+1); IT=IT+(f(k)+f(k+1))/2; end; IL=IL*h; IR=IR*h; IT=IT*h; fprintf(' When N = %i, we find:\n',N); fprintf(' Left-endpoint approximation = %f.\n',IL); fprintf('Right-endpoint approximation = %f.\n',IR); fprintf(' Trapezoidal approximation = %f.\n',IT); % Output from this program:
When N = 10, we find: Left-endpoint approximation = 0.285000. Right-endpoint approximation = 0.385000. Trapezoidal approximation = 0.335000.
New Matab 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
- IL & IR: the left and right endpoint approximation to the integral
- IT: the trapezoidal approximation
Your assignment
A simple pendulum consists of a mass that swings in a vertical plane at the end of a massless rod of length . Suppose that the pendulum is released from rest displaced through an initial angle
. In the absence of friction, the time
required for the pendulum to make a complete swing, called the
, is:
where is the angle the pendulum makes with the vertical at time
.
(a) Obtain a proper integral by substituting:
and then making the change of variable:
(b) Evaluate the resulting integral from part (a) using the numerical integration to approximate the period of the pendulum
for ,
, and
.
(c) For part (b), answer the following questions:
- Run the code with N=10, N=100, and N=1000.
- For each approximation, find the number of points that is needed for the value of the integral to be accurate 3 decimal digits?
- How much better is the trapezoidal rule than the other two? Explain this result using the theory given in the textbook and in lecture.
- BONUS QUESTION Write a program to approximate the integral using Simpson's rule. How many points are needed to achieve the same accuracy as you found for the trapezoidal rule with 1000 points?