---
title: "Lab: approximation and quadrature in code"
heading: Chebyshev coefficients, Runge's phenomenon, Gauss rules, singularities and lobe sums
eyebrow: A13 · Lesson 21 · Lab: approximation and quadrature in code
xp: 60
---

::: hook
Lessons 11 to 20 built approximations and integration rules on paper. Here you'll run them. You'll compute Chebyshev coefficients from a dozen samples and see them match the exact values, reproduce Runge's phenomenon and its cure, watch Gauss–Legendre quadrature gain two or three digits per extra point, remove a singularity by substitution, and accelerate the slowly converging integral of sin x / x by averaging lobe sums.
:::

::: play
- The dots are the errors of Gauss–Legendre rules with n points on $\int_{-1}^1e^x\,dx$, on a log scale: $7.7 \times 10^{-3}$, $6.5 \times 10^{-5}$, $3.0 \times 10^{-7}$, $8.2 \times 10^{-10}$ for n = 2 to 5.
- The line through them falls by roughly two to three digits per point, the signature of spectral convergence for an entire integrand.
- Compare Simpson's rule, whose error with the same number of points falls only as $n^{-4}$.
:::

```sim plot
view: graph
x: n = 2..5
y: err = 0.0000000001..0.1 log
points: 2, 0.0077063; 3, 0.0000654586; 4, 0.000000295131; 5, 0.000000000824777 | label: Gauss–Legendre error | color: ch1
plot: 0.0077063*(2/n)^4 | label: if it fell like Simpson's | color: ch3 | dashed
```

::: predict
## You fit a degree-10 polynomial through 11 points of $\frac{1}{1 + 25x^2}$ and then through 11 Chebyshev points. Roughly how do the worst errors compare?

- [ ] Both about 0.1
- [x] About 1.9 against 0.11
- [ ] About 0.11 against 1.9
- [ ] Both below $10^{-3}$

::: reveal
About 1.9 for equally spaced points and 0.11 for Chebyshev points. You'll reproduce both numbers below with `np.polyfit`. The equally spaced fit oscillates wildly near the ends; the Chebyshev fit spreads its error evenly.
:::
:::

::: nameit
## Chebyshev coefficients from samples

Sample f at $x_j = \cos\theta_j$ with $\theta_j = \frac{(j + \frac12)\pi}{N}$, j = 0, …, N − 1, and compute $c_k = \frac2N\sum_jf(x_j)\cos k\theta_j$. That's the midpoint rule on the integral formula of lesson 13, and since the integrand is periodic in θ it's spectrally accurate: a dozen samples give the first several coefficients to full precision. (The series uses $\frac{c_0}{2}$ for the constant term.)

## Gauss–Legendre in NumPy

`t, w = np.polynomial.legendre.leggauss(n)` returns nodes and weights on [−1, 1]. For [a, b], use $x = \frac{a + b}{2} + \frac{b - a}{2}t$ and multiply the weights by $\frac{b - a}{2}$.

## Lobes

For $\int_0^\infty\frac{\sin x}{x}dx$, integrate each lobe $[k\pi, (k + 1)\pi]$ with a Gauss rule, form partial sums, and average neighbors repeatedly (Euler's transform, lesson 20). In NumPy, `np.sinc(x / np.pi)` is $\frac{\sin x}{x}$, with the value 1 at 0 built in.
:::

::: example
## Compute the first Chebyshev coefficients of $e^x$ from 12 samples.

::: solution
1. **The sums.** With N = 12 and $\theta_j = \frac{(j + 0.5)\pi}{12}$, compute
   $$\frac{2}{12}\sum_je^{\cos\theta_j}\cos k\theta_j$$
   For k = 0 to 5 they give 2.532132, 1.130318, 0.271495, 0.044337, 0.005474, 0.000543.
2. **Compare with the exact values.** These match $2I_k(1)$ to every digit shown. The constant term of the series is half the first, 1.266066, as in lesson 13.
3. **Why twelve samples are enough.** The coefficients fall so fast that the aliasing error, from coefficients beyond k = 12, is below $10^{-13}$.

**Answer:** 2.532132, 1.130318, 0.271495, 0.044337, 0.005474 and 0.000543 for k = 0 to 5, matching $2I_k(1)$.
:::
:::

::: example
## How fast does Gauss–Legendre quadrature converge on $\int_{-1}^1e^x\,dx = e - \frac1e$?

::: solution
1. **The errors.** With 2, 3, 4 and 5 points they are $-7.7 \times 10^{-3}$, $-6.5 \times 10^{-5}$, $-3.0 \times 10^{-7}$ and $-8.2 \times 10^{-10}$.
2. **The rate.** Each extra point gains about 2 to 2.6 digits, more as n grows.
3. **Why.** An n-point rule is exact for polynomials of degree 2n − 1, and $e^x$'s Taylor terms shrink factorially, so the error falls faster than any power of n.
4. **Compare with the trapezoid rule.** Five function evaluations give nine digits, which the trapezoid rule would need about 30 000 evaluations to match.

**Answer:** faster than any power of n: each point adds about 2 to 2.6 digits, and five points give nine digits.
:::
:::

::: check
given: d = 5 | 8 | 11
answer: ceil((d + 1)/2)
tolerance: 0

## What is the smallest Gauss–Legendre rule that integrates every polynomial of degree {d} exactly?

::: right
Right. An n-point rule is exact through degree 2n − 1.
:::

::: misses
- [d + 1] That's what an interpolatory rule with fixed nodes needs; Gauss rules choose their nodes and need half as many.
- [any] Solve $2n - 1 \ge d$.
:::
:::

::: check
given: a = 0.0077 | 0.00065; b = 0.000003 | 0.0000003
answer: log(a/b)
tolerance: 1%

## A rule's error falls from {a} to {b} with one more point. How many decimal digits did that point gain?

::: right
Right. $\log_{10}$ of the ratio of errors.
:::

::: misses
- [ln(a/b)] Use base 10 for decimal digits.
- [any] $\log_{10}\frac ab$.
:::
:::

::: check
kind: python

## Set `c` to the list of Chebyshev coefficients $c_0$ to $c_5$ of $e^x$, from N = 12 samples with $c_k = \frac2N\sum_jf(\cos\theta_j)\cos k\theta_j$ and $\theta_j = \frac{(j + 1/2)\pi}{N}$.

```python starter
import numpy as np

c = [0.0] * 6
print(c)
```

```python solution
import numpy as np

N = 12
theta = (np.arange(N) + 0.5) * np.pi / N
f = np.exp(np.cos(theta))
c = [2 / N * np.sum(f * np.cos(k * theta)) for k in range(6)]
print(c)
```

```python tests
expected = [2.532132, 1.130318, 0.271495, 0.044337, 0.005474, 0.000543]
assert all(abs(a - b) < 1e-6 for a, b in zip(c, expected)), f"Expect 2 I_k(1): {expected}; got {c}."
```

::: right
Right. Twelve samples give the coefficients to full precision.
:::
:::

::: check
kind: python

## Write `interp_err(nodes)` returning the worst error, on 20 001 points of [−1, 1], of the polynomial through `nodes` for $f = \frac{1}{1 + 25x^2}$ (use `np.polyfit` and `np.polyval`). Set `equal` for 11 equally spaced nodes and `cheb` for the 11 Chebyshev nodes $\cos\frac{(2i + 1)\pi}{22}$.

```python starter
import numpy as np

def interp_err(nodes):
    return 0.0

equal = interp_err(np.linspace(-1, 1, 11))
cheb = interp_err(np.cos((2 * np.arange(11) + 1) * np.pi / 22))
print(equal, cheb)
```

```python solution
import numpy as np

f = lambda x: 1 / (1 + 25 * x * x)
xx = np.linspace(-1, 1, 20001)

def interp_err(nodes):
    coeffs = np.polyfit(nodes, f(nodes), len(nodes) - 1)
    return np.max(np.abs(np.polyval(coeffs, xx) - f(xx)))

equal = interp_err(np.linspace(-1, 1, 11))
cheb = interp_err(np.cos((2 * np.arange(11) + 1) * np.pi / 22))
print(equal, cheb)
```

```python tests
assert abs(equal - 1.9157) < 2e-3, f"Equally spaced nodes give a worst error of 1.916; got {equal}."
assert abs(cheb - 0.10915) < 2e-4, f"Chebyshev nodes give 0.109; got {cheb}."
```

::: right
Right. 1.92 against 0.109: same degree, same function, only the nodes differ.
:::
:::

::: check
kind: python

## Use `np.polynomial.legendre.leggauss` to set `errs` to the errors of the n-point rules, n = 2 to 5, on $\int_{-1}^1e^x\,dx$ (computed minus exact).

```python starter
import numpy as np

errs = [0.0] * 4
print(errs)
```

```python solution
import numpy as np

exact = np.e - 1 / np.e
errs = []
for n in range(2, 6):
    t, w = np.polynomial.legendre.leggauss(n)
    errs.append(np.sum(w * np.exp(t)) - exact)
print(errs)
```

```python tests
import numpy as np
assert abs(errs[0] + 7.7063e-3) < 1e-6 and abs(errs[3] + 8.2478e-10) < 1e-12, f"Expect -7.7e-3 for 2 points and -8.2e-10 for 5; got {errs}."
assert all(abs(errs[i + 1]) < abs(errs[i]) / 100 for i in range(3)), "Each extra point should gain at least two digits."
```

::: right
Right. Two to nearly three digits per point, from a rule that's exact through degree 2n − 1.
:::
:::

::: check
kind: python

## Compute $\int_0^1\frac{\cos x}{\sqrt x}dx$ by substituting $x = t^2$ and applying the 20-point Gauss–Legendre rule on [0, 1]. Set `value`.

```python starter
import numpy as np

t, w = np.polynomial.legendre.leggauss(20)
value = 0.0
print(value)
```

```python solution
import numpy as np

t, w = np.polynomial.legendre.leggauss(20)
u = (t + 1) / 2
value = np.sum(w / 2 * 2 * np.cos(u**2))
print(value)
```

```python tests
assert abs(value - 1.8090484758) < 1e-9, f"The integral is 1.809048476; got {value}."
```

::: right
Right. 1.809048476 to ten digits. Without the substitution, the singular integrand would defeat the Gauss rule.
:::
:::

::: check
kind: python

## Integrate each of the first 8 lobes of $\frac{\sin x}{x}$ with the 40-point Gauss rule, form the partial sums `S`, then average neighbors three times. Set `last` to the final averaged value.

```python starter
import numpy as np

S = np.zeros(8)
last = S[-1]
print(last)
```

```python solution
import numpy as np

t, w = np.polynomial.legendre.leggauss(40)
lobes = []
for k in range(8):
    x = (k + 0.5) * np.pi + np.pi / 2 * t
    lobes.append(np.sum(w * np.pi / 2 * np.sinc(x / np.pi)))
S = np.cumsum(lobes)
A = S.copy()
for _ in range(3):
    A = (A[:-1] + A[1:]) / 2
last = A[-1]
print(S[-1], last)
```

```python tests
import numpy as np
assert abs(S[0] - 1.8519370) < 1e-6, f"The first lobe is Si(pi) = 1.851937; got {S[0]}."
assert abs(S[-1] - np.pi / 2) > 0.03, "The raw partial sum should still be far from pi/2."
assert abs(last - np.pi / 2) < 2e-4, f"Three rounds of averaging should land within 2e-4 of pi/2; got {last}."
```

::: right
Right. 1.57093, within $1.4 \times 10^{-4}$ of $\frac\pi2$, from partial sums still 0.04 away.
:::
:::

::: explain
## Why do a dozen samples give Chebyshev coefficients to full precision, when quadrature usually needs many more points?

::: model
Substituting $x = \cos\theta$ turns the Chebyshev coefficient integral into the Fourier cosine coefficient of the periodic, smooth function $f(\cos\theta)$. The midpoint rule on a periodic integrand doesn't suffer the endpoint errors that normally limit it; its only error is aliasing, where coefficient k picks up contributions from coefficients near 2N − k and beyond. For an analytic function those far coefficients are smaller than rounding error once N exceeds a modest number, so the computed coefficients are exact to the last digit. The same reasoning explains why the trapezoid rule is spectrally accurate for periodic functions.
:::
:::

::: practice

::: check
given: d = 1..30 int
answer: ceil((d + 1)/2)
tolerance: 0

## Gauss points needed for degree {d}?

::: misses
- [any] $2n - 1 \ge d$.
:::
:::

::: check
given: a = 0.001 | 0.00002; b = 0.000004 | 0.0000000001
answer: log(a/b)
tolerance: 1%

## Digits gained from {a} to {b}?

::: misses
- [any] $\log_{10}\frac ab$.
:::
:::
:::
