This notebook is a modified and annotated version of the example shown in class November 26, 2015.
It demonstrates how to implement the trapezoidal rule for computing an approximate value for a definite integral.
%pylab
We set up a simple example: Find the integral of the function f(x)=x^2 on the interval [0,1].
To make the prodecure more general (cf. Homework Set 8), we take integration nodes which are not equidistantly spaced. The following cell just sets up random nodes in the interval [0,1]. The details of this do not matter for the purpose of understanding the trapezoidal rule and shall not be explained further.
x=cumsum(rand(10))
x=r_[0,x]/x[-1]
x
Now let's compute an array containing the corresponding values of the function f(x)=x^2:
f=x**2
f
For the trapezoidal rule, we need to compute the width of each integration bin. An array containing the upper ends of the integration bins is provided by
x[1:]
An array containing the corresponding lower ends of the integration bins is provided by
x[:-1]
Therefore, an array with the bin widths is computed as
dx=x[1:]-x[:-1]
In exactly the same way, an array with the average height of the function in each bin is given by
h=(f[1:]+f[:-1])/2
The array containing the area of each bin is therefore obtained by
dx*h
The total area, approximating the integral, is therefore given by
sum(dx*h)
The Fundamental Theorem of Calculus tells us that the exact area under the graph of f on [0,1] is
1/3.
We see that the computed value is rather close, but not exact. The approximation will get better by taking more bins, i.e, replacing the size parameter 10 in Cell 2 by a larger value.