57. Numerical integration: Part II#

Anne Kværnø, André Massing

Date: Jan 28, 2021

import matplotlib.pyplot as plt
import numpy as np
from IPython.core.display import HTML
from numpy import pi


def css_styling():
    try:
        with open("tma4125.css") as f:
            styles = f.read()
            return HTML(styles)
    except FileNotFoundError:
        pass  # Do nothing


# Comment out next line and execute this cell to restore the default notebook style
css_styling()

As usual, we import the necessary modules before we get started.

%matplotlib inline

newparams = {
    "figure.figsize": (8.0, 4.0),
    "axes.grid": True,
    "lines.markersize": 8,
    "lines.linewidth": 2,
    "font.size": 14,
}
plt.rcParams.update(newparams)

58. General construction of quadrature rules#

In the following, you will learn the steps on how to construct realistic algorithms for numerical integration, similar to those used in software like Matlab of SciPy. The steps are:

Construction.

  1. Choose n+1 distinct nodes on a standard interval I, often chosen to be I=[1,1].

  2. Let pn(x) be the polynomial interpolating some general function f in the nodes, and let the Q[f](1,1)=I[pn](1,1).

  3. Transfer the formula Q from [1,1] to some interval [a,b].

  4. Design a composite formula, by dividing the interval [a,b] into subintervals and applying the quadrature formula on each subinterval.

  5. Find an expression for the error E[f](a,b)=I[f](a,b)Q[f](a,b).

  6. Find an expression for an estimate of the error, and use this to create an adaptive algorithm.

In this course, we will not have the time to cover the last two steps.

59. Constructing quadrature rules on a single interval#

We have already seen in the previous Lecture how quadrature rules on a given interval [a,b] can be constructed using polynomial interpolation.

For n+1 quadrature points {xi}i=0n[a,b], we compute weights by

wi=abi(x)dxfor i=0,,n.

where i(x) are the cardinal functions associated with {xi}i=0n satisfying i(xj)=δij for i,j=0,1,,n. The resulting quadrature rule has (at least) degree of exactness equal to n.

But how to you proceed if you know want to compute an integral on a different interval, say [c,d]? Do we have to reconstruct all the cardinal functions and recompute the weights?

The answer is NO! One can easily transfer quadrature points and weights from one interval to another. One typically choose the simple reference interval I^=[1,1]. Then you determine some n+1 quadrature points {x^i}i=0n[1,1] and quadrature weights {w^i}i=0n to define a quadrature rule Q(I^)

The quadrature points can then be transferred to an arbitrary interval [a,b] to define a quadrature rule Q(a,b) using the transformation

x=ba2x^+b+a2,sodx=ba2dx^,

and thus we define {xi}i=0n and {wi}i=0n by

xi=ba2x^i+b+a2,wi=ba2w^ifor i=0,n.

59.1. Example 1: Simpson’s rule#

  • Choose standard interval [1,1]. For Simpson’s rule, choose the nodes t0=1, t1=0 and t2=1. The corresponding cardinal functions are

    • 0=12(t2t),1(t)=1t2,2(t)=12(t2+t).

    which gives the weights

    • w0=110(t)dt=13,w1=111(t)dt=43,w2=112(t)dt=13

    such that

    • 11f(t)dt11p2(t)dt=i=02wif(ti)=13[f(1)+4f(0)+f(1)].

  • After transferring the nodes and weights, Simpson’s rule over the interval [a,b] becomes

    • S(a,b)=ba6[f(a)+4f(c)+f(b)],c=b+a2.

60. Composite quadrature rules#

To generate more accurate quadrature rule Q(a,b) we have in principle two possibilities:

  • Increase the order of the interpolation polynomial used to construct the quadrature rule.

  • Subdivide the interval [a,b] into smaller subintervals and apply a quadrature rule on each of the subintervals, leading to Composite Quadrature Rules which we will consider next.

Select m2 and divide [a,b] into m equally spaced subintervals [xi1,xi] defined by xi=a+ih with h=(ba)/m for i=1,,m. Then for a given quadrature rule Q[](xi1,xi) the corresponding composite quadrature rule CQ[]([xi1,xi]i=1m) is given by

(1)abfdxCQ[f]([xi1,xi]i=1m)=i=1mQ[f](xi1,xi).

60.1. Composite trapezoidal rule#

Using the trapezoidal rule T[f](xi1,xi)=h2f(xi1)+h2f(xi) the resulting composite trapezoidal rule is given by

abfdxCT[f]([xi1,xi]i=1m)=h[12f(x0)+f(x1)++f(xm1)+12f(xm)]

60.2. Exercise 1: Testing the accuracy of the composite trapezoidal rule#

Have a look at the CT function which implements the composite trapezoidal rule:

def CT(f, a, b, m):
    """Computes an approximation of the integral f
    using the composite trapezoidal rule.
    Input:
        f:  integrand
        a:  left interval endpoint
        b:  right interval endpoint
        m:  number of subintervals
    """
    x = np.linspace(a, b, m + 1)
    h = float(b - a) / m
    fx = f(x[1:-1])
    ct = h * (np.sum(fx) + 0.5 * (f(x[0]) + f(x[-1])))
    return ct

Use this function to compute an approximate value of integral

I(0,1)=01cos(π2x)=2π=0.636619.

for m=4,8,16,32,64 corresponding to h=22,23,24,25,26. Tabulate the corresponding quadrature errors I(0,1)Q(0,1). What do you observe?

# Insert your code here.

Solution.

# Define function


def f(x):
    return np.cos(pi * x / 2)


# Exact integral
int_f = 2 / pi

# Interval
a, b = 0, 1

# Compute integral numerically
for m in [4, 8, 16, 32, 64]:
    cqr_f = CT(f, a, b, m)
    print(f"Number of subintervals m = {m}")
    print(f"Q[f] = {cqr_f}")
    print(f"I[f] - Q[f] = {int_f - cqr_f:.10e}")
Number of subintervals m = 4
Q[f] = 0.6284174365157311
I[f] - Q[f] = 8.2023358519e-03
Number of subintervals m = 8
Q[f] = 0.6345731492255537
I[f] - Q[f] = 2.0466231420e-03
Number of subintervals m = 16
Q[f] = 0.6361083632808496
I[f] - Q[f] = 5.1140908673e-04
Number of subintervals m = 32
Q[f] = 0.6364919355013015
I[f] - Q[f] = 1.2783686628e-04
Number of subintervals m = 64
Q[f] = 0.636587814113642
I[f] - Q[f] = 3.1958253939e-05

60.2.1. Remarks#

We observe that for each doubling of the number of subintervals we decrease the error by a fourth. That means that if we look at the quadrature error I[f]CT[f] as a function of the number of subintervals m (or equivalently as a function of h), then |I[f]CT[f]|Cm2=Ch2.

60.3. Error estimate for the composite trapezoidal rule#

We will now theoretically explain the experimentally observed convergence rate in the previous Exercise 1: Testing the accuracy of the composite trapezoidal rule.

First we have to recall the error estimate for for the trapezoidal rule on a single interval [a,b]. If fC2(a,b), then there is a ξ(a,b) such that

I[f]T[f]=(ba)312f(ξ).

60.4. Theorem 1: Quadrature error estimate for composite trapezoidal rule#

Let fC2(a,b), then the quadrature error I[f]CT[f] for the composite trapezoidal rule can be estimated by

(2)|I[f]CT[f]|M212(ba)3m2=M212h2(ba)

where M2=maxξ[a,b]|f(ξ)|.

Proof.

|I[f]CT[f]|=|i=1m[xi1xif(x)dx(h2f(xi1)+h2f(xi))]|i=1mh312|f(ξi)|M2i=1m(h)312=M2h312m(ba)h=M212h2(ba)=M212(ba)3m2.

60.5. Interlude: Convergence of h-dependent approximations#

Let X be the exact solution, and X(h) some numerical solution depending on a parameter h, and let e(h) be the norm of the error, so e(h)=XX(h). The numerical approximation X(h) converges to X if e(h)0 as h0. The order of the approximation is p if there exists a positive constant M such that $e(h)Mhp$

The Big O-notation we can simply write $e(h)=O(hp) as h0.ThisisoftenusedwhenwearenotdirectlyinterestedinanyexpressionfortheconstantM$, we only need to know it exists.

Again, we see that a higher approximation order p leads for small values of h to a better approximation of the solution. Thus we are generally interested in approximations of higher order.

60.5.1. Numerical verification#

The following is based on the assumption that e(h)Chp for some unknown constant C. This assumption is often reasonable for sufficiently small h.

Choose a test problem for which the exact solution is known and compute the error for a decreasing sequence of hk’s, for instance hk=H/2k, k=0,1,2,. The procedure is then quite similar to what was done for iterative processes.

e(hk+1)Chk+1pe(hk)Chkpe(hk+1)e(hk)(hk+1hk)pplog(e(hk+1)/e(hk))log(hk+1/hk)

For one refinement step where one passes from hkhk+1, the number $EOC(k)log(e(hk+1)/e(hk))log(hk+1/hk)$ is often called the “Experimental order of convergence at refinement level k”

Since $e(h)Chploge(h)logC+ploghaplotofe(h)asafunctionofhusingalogarithmicscaleonbothaxes(aloglogplot)willbeastraightlinewithslopep$. Such a plot is referred to as an error plot or a convergence plot.

60.6. Exercise 1 (extension): Examine the convergence order of composite trapezoidal rule#

# Insert your code here.

Solution

# Define function


def f(x):
    return np.cos(pi * x / 2)


# Exact integral
int_f = 2 / pi

# Interval
a, b = 0, 1

errs = []
hs = []

# Compute integral numerically
for m in [4, 8, 16, 32, 64]:
    cqr_f = CT(f, a, b, m)
    print(f"Number of subintervals m = {m}")
    print(f"Q[f] = {cqr_f}")
    err = int_f - cqr_f
    errs.append(err)
    hs.append((b - a) / m)
    print(f"I[f] - Q[f] = {err:.10e}")

hs = np.array(hs)
errs = np.array(errs)
eoc = np.log(errs[1:] / errs[:-1]) / np.log(hs[1:] / hs[:-1])
print(eoc)
plt.loglog(hs, errs, "bo-")
Number of subintervals m = 4
Q[f] = 0.6284174365157311
I[f] - Q[f] = 8.2023358519e-03
Number of subintervals m = 8
Q[f] = 0.6345731492255537
I[f] - Q[f] = 2.0466231420e-03
Number of subintervals m = 16
Q[f] = 0.6361083632808496
I[f] - Q[f] = 5.1140908673e-04
Number of subintervals m = 32
Q[f] = 0.6364919355013015
I[f] - Q[f] = 1.2783686628e-04
Number of subintervals m = 64
Q[f] = 0.636587814113642
I[f] - Q[f] = 3.1958253939e-05
[2.00278934 2.00069577 2.00017385 2.00004346]
[<matplotlib.lines.Line2D at 0x7fee1892c680>]
../_images/64169a57fc7a5aac855437112ca78d1466e25ebf46cb9d5ff406ca5f42cf6fef.png

60.7. Exercise 2: Composite Simpson’s rule#

We can now play the exact same game to construct and analyze a Composite Simpson’s rule. In this set of exercises you are ask to develop the code and theory for the composite Simpson’s rule. This will be part of the next homework assignment.

a) Start from Simpson’s rule

S[f](xi1,xi)=h6(f(xxi1)+4f(xi1/2)+f(xi)),

where xi1/2=xi1+xi2 is the midpoint of the interval [xi1,xi].

Show that the resulting composite Simpson’s rule is given by

abfdxCSR[f]([xi,xi+1]i=1m)=h6[f(x0)+4f(xx1/2)+2f(x1)+4f(x3/2)+2f(x2)++2f(xm1)+4f(xxm1/2)+f(xm)].

b) Implement the composite Simpson’s rule. Use this function to compute an approximate value of integral

I(0,1)=01cos(π2x)=2π=0.636619.

for m=4,8,16,32,64 corresponding to h=22,23,24,25,26. Tabulate the corresponding quadrature errors I(0,1)Q(0,1). What do you observe? How does it compare to the composite trapezoidal rule?

# Insert your code here.

c) Recall the error estimate for Simpson’s rule on a single interval, stating that there is a ξ(a,b) such that

I[f]Q[f]=(ba)52880f4(ξ).

whenever fC4(a,b). Start from this estimate and prove the following theorem.

60.8. Theorem 2: Quadrature error estimate for composite Simpon’s rule#

Let fC4(a,b), then the quadrature error I[f]CT[f] for the composite trapezoidal rule can be estimated by

(3)|I[f]CSR[f]|M42880(ba)5m4=M42880h4(ba)

where M4=maxξ[a,b]|f(4)(ξ)|.

Proof.

Insert your proof here.