TExcelTAD
Home › Numerical Methods › Numerical Methods Exercises

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 x2−106x+1=0x^2 - 10^6x + 1 = 0 accurately (Catastrophic Cancellation). The textbook formula gives the small root badly; use x1x2=c/ax_1x_2 = c/a instead.

python · try it yourself
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:

text
big root  : 1.0000000000e+06
small root: 1.0000000000e-06
check a*x^2 + b*x + c at small root: 0.0e+00
Solution
python · try it yourself
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 −b−d-b - d of two numbers near 10610^6 loses about 11 digits; dividing cc by the well-computed big root loses none.

Exercise 2: Kepler's equation by Newton

Solve Kepler's equation E−esin⁡E=ME - e\sin E = M for the eccentric anomaly EE with e=0.9e = 0.9, M=0.5M = 0.5 (Newton's Method). Start from E0=πE_0 = \pi (a safe start for large ee), stop when the step is below 10−1410^{-14}, and count the iterations.

python · try it yourself
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:

text
E = 1.384412720202163 after 7 iterations, residual 1.1e-16
Solution
python · try it yourself
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

f′(E)=1−ecos⁡E≥1−e=0.1>0f'(E) = 1 - e\cos E \ge 1 - e = 0.1 > 0, so the derivative never vanishes; the start E0=πE_0 = \pi avoids the slow region near E=0E = 0 where f′f' 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 4×44 \times 4 system whose first pivot is zero.

python · try it yourself
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:

text
x = [-3. -6. 10.  9.]
residual: 0.0e+00
Solution
python · try it yourself
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 y=c0+c1t+c2t2y = c_0 + c_1t + c_2t^2 to noisy data by the thin QR factorization (The QR Factorization): solve Rc=QTyR\mathbf{c} = Q^T\mathbf{y}.

python · try it yourself
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:

text
coefficients: [ 0.9922 -1.9901  0.5005]
residual norm: 0.2554
Solution
python · try it yourself
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 1,−2,0.51, -2, 0.5; the residual norm is about 40⋅0.05≈0.3\sqrt{40} \cdot 0.05 \approx 0.3, 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.

python · try it yourself
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:

text
power iteration: 7.287992138960
eigvalsh       : 7.287992138960
Solution
python · try it yourself
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 ∫0πsin⁡x1+x2 dx\int_0^{\pi}\frac{\sin x}{1 + x^2}\,dx with composite Simpson (n=16n = 16 subintervals, 17 points) and with 8-point Gauss-Legendre (Gaussian Quadrature), and compare both with quad.

python · try it yourself
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:

text
Simpson (17 points): error 6.4e-05
Gauss   (8 points) : error 5.0e-06
Solution
python · try it yourself
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 r′′=−r∣r∣3\mathbf{r}'' = -\frac{\mathbf{r}}{\lvert\mathbf{r}\rvert^3}, r(0)=(1,0)\mathbf{r}(0) = (1, 0), r′(0)=(0,1)\mathbf{r}'(0) = (0, 1), for one period 2π2\pi with RK4 and 200 steps (Runge-Kutta Methods). The orbit should close.

python · try it yourself
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:

text
position after one period: (0.99999999, 0.00000017)
distance from the start: 1.65e-07
Solution
python · try it yourself
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 10−710^{-7}.

Exercise 8: Conjugate gradients for a BVP

Discretize −u′′=12x2-u'' = 12x^2, u(0)=u(1)=0u(0) = u(1) = 0, with n=99n = 99 interior points (Finite Differences for BVPs) and solve with your own conjugate gradient loop (Conjugate Gradients). The exact solution is u=x−x4u = x - x^4.

python · try it yourself
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:

text
CG iterations: 99
max error vs x - x^4: 2.50e-05
Solution
python · try it yourself
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 O(h2)O(h^2) discretization error, not the solver's.

Test yourself

You must solve Ax=bA\mathbf{x} = \mathbf{b} for 1000 right-hand sides with the same dense AA. What do you do?

  1. Call np.linalg.solve 1000 times
  2. Factor A=PLUA = PLU once and reuse it
  3. Compute A−1A^{-1} and multiply
  4. Use bisection

An ODE solver takes millions of tiny steps on a solution that looks smooth. The most likely cause is…

  1. a bug in NumPy
  2. stiffness: switch to an implicit method such as BDF or Radau
  3. too loose a tolerance
  4. the problem has no solution

Which statement about a backward stable algorithm is true?

  1. It always gives 16 correct digits
  2. Its answer is exact for slightly perturbed data, so its forward error is about κ\kappa times machine precision
  3. It is never affected by conditioning
  4. It needs no floating point