The Composite Trapezoid Rule (and Composite Midpoint Rule)

Last updated on April 5 (after class) with the example of the Composite Midpoint Rule.

Write a Python function that can approximate any definite integral \(I = \displaystyle \int_a^b f(x)\,dx\) using the Composite Trapezoid Rule with \(n\) sub-intervals of equal width, \(T_n\).

  • The input should specify the function \(f\) to integrate, the interval \([a,b]\), and the number \(n\) of sub-intervals to use.

  • The output will be just the approximation value of the integral; error estimates and tolerances are coming later!

  • As usual add a code cell with testing of this on some examples, as suggested in the section on Test Cases for Integration.

Update: The Composite Midpoint Rule

As the Composite Midpoint Rule is used in Recursive Trapezeoid Rule and the Romberg Method, I will illustrate with it:

\[\int_a^b f(x)\, dx \approx M_n = \sum_{i=1}^n f(a + (i-1/2)h) \quad \text{where } h=(b-a)/n \]

Python has a function sum, and can get an array of the \(x\) values with numpy.linspace, so ths can be done as folllows:

import numpy as np
def compositeMidpoint(f, a, b, n, demoMode=False):
    h = (b-a)/n
    x = np.linspace(a+h/2, b-h/2, n)
    if demoMode:
        print(f"With {a=}, {b=}, {n=}, {h=} and the nodes are {x}")
    M_n = sum(f(x)) * h
    return M_n
def f(x): return 1/x**2
a=1
b=3
I_exact = 2.0/3.0

M_10 = compositeMidpoint(f, a, b, 10, demoMode=True)
error = M_10 - I_exact
print(f"{M_10=}, {error=}")
print()
M_100 = compositeMidpoint(f, a, b, 100, demoMode=False)
error = M_100 - I_exact
print(f"{M_100=}, {error=}")
With a=1, b=3, n=10, h=0.2 and the nodes are [1.1 1.3 1.5 1.7 1.9 2.1 2.3 2.5 2.7 2.9]
M_10=0.6635018670317585, error=-0.003164799634908122

M_100=0.6666345725472225, error=-3.20941194441593e-05