Numerical Methods Exercises
Time to practise the whole course. Each exercise has a starter program that runs but does not do the job yet. Replace the TODO parts, press ▶ Run, and compare your result with the expected output. The output block under each starter shows what the unfinished starter prints.
Tip: Test every method on a problem with a known answer, and check that the error shrinks at the predicted rate when you refine. A method that converges at the right rate is almost certainly implemented correctly.
| # | Exercise | Practises |
|---|---|---|
| 1 | Roots without cancellation | floating point, stable formulas |
| 2 | Kepler's equation by Newton | Newton's method, stopping criteria |
| 3 | LU with partial pivoting | elimination, permutations |
| 4 | Least squares by QR | QR factorization, triangular solves |
| 5 | The dominant eigenvalue | power iteration, Rayleigh quotient |
| 6 | Simpson versus Gauss | quadrature, convergence rates |
| 7 | An RK4 orbit | Runge-Kutta, systems of ODEs |
| 8 | Conjugate gradients for a BVP | finite differences, iterative solvers |
Exercise 1: Roots without cancellation
Compute both roots of accurately (Catastrophic Cancellation). The textbook formula gives the small root badly; use instead.
import numpy as np
a, b, c = 1.0, -1e6, 1.0
d = np.sqrt(b * b - 4 * a * c)
big = (-b + d) / (2 * a)
small = (-b - d) / (2 * a) # TODO: compute the small root from big with Vieta's formula
print(f"big root : {big:.10e}")
print(f"small root: {small:.10e}")
print(f"check a*x^2 + b*x + c at small root: {a * small**2 + b * small + c:.1e}")big root : 1.0000000000e+06
small root: 1.0000076145e-06
check a*x^2 + b*x + c at small root: -7.6e-06
Expected output when solved:
big root : 1.0000000000e+06
small root: 1.0000000000e-06
check a*x^2 + b*x + c at small root: 0.0e+00Solution
import numpy as np
a, b, c = 1.0, -1e6, 1.0
d = np.sqrt(b * b - 4 * a * c)
big = (-b + d) / (2 * a)
small = c / (a * big)
print(f"big root : {big:.10e}")
print(f"small root: {small:.10e}")
print(f"check a*x^2 + b*x + c at small root: {a * small**2 + b * small + c:.1e}")big root : 1.0000000000e+06
small root: 1.0000000000e-06
check a*x^2 + b*x + c at small root: 0.0e+00
The subtraction of two numbers near loses about 11 digits; dividing by the well-computed big root loses none.
Exercise 2: Kepler's equation by Newton
Solve Kepler's equation for the eccentric anomaly with , (Newton's Method). Start from (a safe start for large ), stop when the step is below , and count the iterations.
import numpy as np
e, M = 0.9, 0.5
E = np.pi
for k in range(1, 51):
step = 0.0 # TODO: Newton step f(E)/f'(E) with f(E) = E - e sin E - M
E -= step
if abs(step) < 1e-14:
break
print(f"E = {E:.15f} after {k} iterations, residual {E - e * np.sin(E) - M:.1e}")E = 3.141592653589793 after 1 iterations, residual 2.6e+00
Expected output when solved:
E = 1.384412720202163 after 7 iterations, residual 1.1e-16Solution
import numpy as np
e, M = 0.9, 0.5
E = np.pi
for k in range(1, 51):
step = (E - e * np.sin(E) - M) / (1 - e * np.cos(E))
E -= step
if abs(step) < 1e-14:
break
print(f"E = {E:.15f} after {k} iterations, residual {E - e * np.sin(E) - M:.1e}")E = 1.384412720202163 after 7 iterations, residual 1.1e-16
, so the derivative never vanishes; the start avoids the slow region near where is small.
Exercise 3: LU with partial pivoting
Complete the elimination loop of an LU factorization with partial pivoting (Row Pivoting) and use it to solve a system whose first pivot is zero.
import numpy as np
from scipy.linalg import solve_triangular
def plu(A):
n = len(A)
U = A.astype(float).copy(); L = np.eye(n); perm = np.arange(n)
for k in range(n - 1):
p = k + np.argmax(np.abs(U[k:, k]))
U[[k, p]] = U[[p, k]]; L[[k, p], :k] = L[[p, k], :k]; perm[[k, p]] = perm[[p, k]]
# TODO: store the multipliers in L[k+1:, k] and eliminate below the pivot in U
return perm, L, U
A = np.array([[0.0, 2, 1, 1], [2, 1, 0, 3], [4, 1, 3, 1], [1, 1, 1, 1]])
b = np.array([7.0, 15, 21, 10])
perm, L, U = plu(A)
x = solve_triangular(U, solve_triangular(L, b[perm], lower=True))
print("x =", np.round(x, 10))
print("residual:", f"{np.linalg.norm(A @ x - b):.1e}")x = [ 0.625 -1.5 5. 5. ]
residual: 9.1e-01
Expected output when solved:
x = [-3. -6. 10. 9.]
residual: 0.0e+00Solution
import numpy as np
from scipy.linalg import solve_triangular
def plu(A):
n = len(A)
U = A.astype(float).copy(); L = np.eye(n); perm = np.arange(n)
for k in range(n - 1):
p = k + np.argmax(np.abs(U[k:, k]))
U[[k, p]] = U[[p, k]]; L[[k, p], :k] = L[[p, k], :k]; perm[[k, p]] = perm[[p, k]]
L[k + 1:, k] = U[k + 1:, k] / U[k, k]
U[k + 1:, k:] -= np.outer(L[k + 1:, k], U[k, k:])
return perm, L, U
A = np.array([[0.0, 2, 1, 1], [2, 1, 0, 3], [4, 1, 3, 1], [1, 1, 1, 1]])
b = np.array([7.0, 15, 21, 10])
perm, L, U = plu(A)
x = solve_triangular(U, solve_triangular(L, b[perm], lower=True))
print("x =", np.round(x, 10))
print("residual:", f"{np.linalg.norm(A @ x - b):.1e}")x = [-3. -6. 10. 9.]
residual: 0.0e+00
Exercise 4: Least squares by QR
Fit to noisy data by the thin QR factorization (The QR Factorization): solve .
import numpy as np
from scipy.linalg import solve_triangular
rng = np.random.default_rng(2026)
t = np.linspace(0, 2, 40)
y = 1.0 - 2.0 * t + 0.5 * t**2 + rng.normal(0, 0.05, t.size)
A = np.column_stack([np.ones_like(t), t, t**2])
Q, R = np.linalg.qr(A)
c = np.zeros(3) # TODO: solve R c = Q^T y
print("coefficients:", np.round(c, 4))
print(f"residual norm: {np.linalg.norm(y - A @ c):.4f}")coefficients: [0. 0. 0.]
residual norm: 4.3480
Expected output when solved:
coefficients: [ 0.9922 -1.9901 0.5005]
residual norm: 0.2554Solution
import numpy as np
from scipy.linalg import solve_triangular
rng = np.random.default_rng(2026)
t = np.linspace(0, 2, 40)
y = 1.0 - 2.0 * t + 0.5 * t**2 + rng.normal(0, 0.05, t.size)
A = np.column_stack([np.ones_like(t), t, t**2])
Q, R = np.linalg.qr(A)
c = solve_triangular(R, Q.T @ y)
print("coefficients:", np.round(c, 4))
print(f"residual norm: {np.linalg.norm(y - A @ c):.4f}")coefficients: [ 0.9922 -1.9901 0.5005]
residual norm: 0.2554
The coefficients are close to the true ; the residual norm is about , the noise level.
Exercise 5: The dominant eigenvalue
Find the largest eigenvalue of the symmetric matrix below by power iteration with the Rayleigh quotient (Power Iteration), and compare with eigvalsh.
import numpy as np
A = np.array([[6.0, 2, 1], [2, 3, 1], [1, 1, 1]])
x = np.ones(3)
for _ in range(60):
pass # TODO: x = A x, then normalize x
lam = x @ A @ x / (x @ x)
print(f"power iteration: {lam:.12f}")
print(f"eigvalsh : {np.linalg.eigvalsh(A)[-1]:.12f}")power iteration: 6.000000000000
eigvalsh : 7.287992138960
Expected output when solved:
power iteration: 7.287992138960
eigvalsh : 7.287992138960Solution
import numpy as np
A = np.array([[6.0, 2, 1], [2, 3, 1], [1, 1, 1]])
x = np.ones(3)
for _ in range(60):
x = A @ x
x /= np.linalg.norm(x)
lam = x @ A @ x / (x @ x)
print(f"power iteration: {lam:.12f}")
print(f"eigvalsh : {np.linalg.eigvalsh(A)[-1]:.12f}")power iteration: 7.287992138960
eigvalsh : 7.287992138960
Exercise 6: Simpson versus Gauss
Integrate with composite Simpson ( subintervals, 17 points) and with 8-point Gauss-Legendre (Gaussian Quadrature), and compare both with quad.
import numpy as np
from scipy.integrate import quad
f = lambda x: np.sin(x) / (1 + x**2)
a, b = 0.0, np.pi
ref = quad(f, a, b, epsabs=1e-14)[0]
x = np.linspace(a, b, 17); h = (b - a) / 16
S = 0.0 # TODO: composite Simpson with the 17 points x
t, w = np.polynomial.legendre.leggauss(8)
G = 0.0 # TODO: map t to [a, b] and form the weighted sum
print(f"Simpson (17 points): error {abs(S - ref):.1e}")
print(f"Gauss (8 points) : error {abs(G - ref):.1e}")Simpson (17 points): error 7.2e-01
Gauss (8 points) : error 7.2e-01
Expected output when solved:
Simpson (17 points): error 6.4e-05
Gauss (8 points) : error 5.0e-06Solution
import numpy as np
from scipy.integrate import quad
f = lambda x: np.sin(x) / (1 + x**2)
a, b = 0.0, np.pi
ref = quad(f, a, b, epsabs=1e-14)[0]
x = np.linspace(a, b, 17); h = (b - a) / 16
y = f(x)
S = h / 3 * (y[0] + y[-1] + 4 * y[1:-1:2].sum() + 2 * y[2:-1:2].sum())
t, w = np.polynomial.legendre.leggauss(8)
G = (b - a) / 2 * np.sum(w * f((a + b) / 2 + (b - a) / 2 * t))
print(f"Simpson (17 points): error {abs(S - ref):.1e}")
print(f"Gauss (8 points) : error {abs(G - ref):.1e}")Simpson (17 points): error 6.4e-05
Gauss (8 points) : error 5.0e-06
With half the function evaluations, Gauss is more than ten times as accurate on this smooth integrand.
Exercise 7: An RK4 orbit
Integrate a circular orbit , , , for one period with RK4 and 200 steps (Runge-Kutta Methods). The orbit should close.
import numpy as np
def f(t, y):
r = y[:2]; v = y[2:]
return np.r_[v, -r / np.linalg.norm(r) ** 3]
n = 200; h = 2 * np.pi / n
y = np.array([1.0, 0.0, 0.0, 1.0])
for i in range(n):
t = i * h
y = y + h * f(t, y) # TODO: replace this Euler step by an RK4 step
print(f"position after one period: ({y[0]:.8f}, {y[1]:.8f})")
print(f"distance from the start: {np.hypot(y[0] - 1, y[1]):.2e}")position after one period: (0.41781466, -1.30450718)
distance from the start: 1.43e+00
Expected output when solved:
position after one period: (0.99999999, 0.00000017)
distance from the start: 1.65e-07Solution
import numpy as np
def f(t, y):
r = y[:2]; v = y[2:]
return np.r_[v, -r / np.linalg.norm(r) ** 3]
n = 200; h = 2 * np.pi / n
y = np.array([1.0, 0.0, 0.0, 1.0])
for i in range(n):
t = i * h
k1 = f(t, y); k2 = f(t + h / 2, y + h / 2 * k1)
k3 = f(t + h / 2, y + h / 2 * k2); k4 = f(t + h, y + h * k3)
y = y + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)
print(f"position after one period: ({y[0]:.8f}, {y[1]:.8f})")
print(f"distance from the start: {np.hypot(y[0] - 1, y[1]):.2e}")position after one period: (0.99999999, 0.00000017)
distance from the start: 1.65e-07
Euler's orbit spirals outwards and misses by a wide margin; RK4 closes the orbit to about .
Exercise 8: Conjugate gradients for a BVP
Discretize , , with interior points (Finite Differences for BVPs) and solve with your own conjugate gradient loop (Conjugate Gradients). The exact solution is .
import numpy as np
import scipy.sparse as sp
n = 99; h = 1 / (n + 1)
x = np.arange(1, n + 1) * h
A = sp.diags([-1, 2, -1], [-1, 0, 1], shape=(n, n), format="csr") / h**2
b = 12 * x**2
u = np.zeros(n); r = b.copy(); p = r.copy(); rr = r @ r
its = 0
while np.sqrt(rr) > 1e-10 * np.linalg.norm(b) and its < 500:
its += 1
break # TODO: one CG iteration (alpha, update u and r, new p); remove this break
print(f"CG iterations: {its}")
print(f"max error vs x - x^4: {np.max(np.abs(u - (x - x**4))):.2e}")CG iterations: 1
max error vs x - x^4: 4.72e-01
Expected output when solved:
CG iterations: 99
max error vs x - x^4: 2.50e-05Solution
import numpy as np
import scipy.sparse as sp
n = 99; h = 1 / (n + 1)
x = np.arange(1, n + 1) * h
A = sp.diags([-1, 2, -1], [-1, 0, 1], shape=(n, n), format="csr") / h**2
b = 12 * x**2
u = np.zeros(n); r = b.copy(); p = r.copy(); rr = r @ r
its = 0
while np.sqrt(rr) > 1e-10 * np.linalg.norm(b) and its < 500:
its += 1
Ap = A @ p
alpha = rr / (p @ Ap)
u += alpha * p
r -= alpha * Ap
rr_new = r @ r
p = r + rr_new / rr * p
rr = rr_new
print(f"CG iterations: {its}")
print(f"max error vs x - x^4: {np.max(np.abs(u - (x - x**4))):.2e}")CG iterations: 99
max error vs x - x^4: 2.50e-05
The remaining error is the discretization error, not the solver's.
Test yourself
You must solve for 1000 right-hand sides with the same dense . What do you do?
- Call
np.linalg.solve1000 times - Factor once and reuse it
- Compute and multiply
- Use bisection
An ODE solver takes millions of tiny steps on a solution that looks smooth. The most likely cause is…
- a bug in NumPy
- stiffness: switch to an implicit method such as BDF or Radau
- too loose a tolerance
- the problem has no solution
Which statement about a backward stable algorithm is true?
- It always gives 16 correct digits
- Its answer is exact for slightly perturbed data, so its forward error is about times machine precision
- It is never affected by conditioning
- It needs no floating point