Numerical Linear Algebra#
Almost every numerical method in the series ends in a linear system or a matrix factorisation. An implicit finite-difference step solves a tridiagonal system, a regression solves the normal equations, correlated random numbers need a Cholesky factor, and a risk decomposition needs an eigenvalue problem. The routines are standard and reliable, and valuation problems come from how they are used: a system that is nearly singular, a normal-equation fit, a correlation matrix that is not valid. This page sets out the methods that matter, shows the errors that come from ill-conditioning, and shows what to do with a correlation matrix that fails.
Where it appears in the series#
Implicit and Crank-Nicolson schemes solve a tridiagonal system at every time step (PDE Methods, Part 2: Implicit & Crank-Nicolson).
Regression, for the continuation value in Advanced Methods, Part 1: Least-Squares Monte Carlo and for curve fitting (Numerical Methods: Regression and Fitting), is a least-squares problem.
Correlated simulation multiplies independent normals by a Cholesky factor of the correlation matrix (Random Numbers & Sampling).
Cubic splines solve a tridiagonal system for the curvatures (Interpolation, Part 1: Flat, Linear & Cubic Methods).
Risk and calibration use the Jacobian of a model and its decomposition (The Jacobian), in Calibration.
Direct solvers#
To solve \(A x = b\) for a square matrix, the standard method is the LU factorisation with row pivoting, \(PA = LU\), followed by two triangular solves. It costs \(O(n^3)\) operations for a dense matrix, and the solve for each new right-hand side costs \(O(n^2)\). Pivoting keeps it stable for almost every matrix that arises.
A banded matrix needs far less. A tridiagonal system, with diagonal \(b_i\), lower diagonal \(a_i\) and upper diagonal \(c_i\), is solved by the Thomas algorithm in \(O(n)\) operations. A forward sweep eliminates the lower diagonal,
and a back substitution gives \(x_n = d_n'\) and \(x_i = d_i' - c_i' x_{i+1}\). It is stable when the matrix is diagonally dominant, \(|b_i| \ge |a_i| + |c_i|\), which is the case for the implicit finite-difference schemes and for the cubic spline system.
Conditioning#
The condition number \(\kappa(A) = \lVert A \rVert \, \lVert A^{-1} \rVert\) measures how much a small change in \(b\) or in \(A\) is magnified in the solution. In floating point arithmetic with relative precision \(\varepsilon \approx 1.1 \times 10^{-16}\), the relative error of a solution is of the order
so a matrix with \(\kappa = 10^{k}\) loses about \(k\) digits. The condition number belongs to the problem and not to the algorithm, and no solver can recover digits that the problem has lost.
A least-squares fit, \(\min \lVert A\beta - y \rVert\), can be solved from the normal equations \(A^\top A \beta = A^\top y\), which are small and fast. They square the condition number, \(\kappa(A^\top A) = \kappa(A)^2\), and so lose twice the digits. A QR factorisation, \(A = QR\), solves \(R\beta = Q^\top y\) and the singular value decomposition \(A = U \Sigma V^\top\) gives \(\beta = V \Sigma^{-1} U^\top y\). Both work with \(\kappa(A)\), and the SVD also shows which directions are poorly determined, the small singular values.
Cholesky and correlation matrices#
A symmetric positive definite matrix has a factorisation \(\Sigma = L L^\top\) with \(L\) lower triangular, at half the cost of LU. To simulate correlated normals, draw independent \(Z \sim N(0, I)\) and set \(X = L Z\), so that \(\operatorname{Cov}(X) = L L^\top = \Sigma\).
A correlation matrix must be symmetric, have a unit diagonal and be positive semi-definite, which means that every eigenvalue is non-negative. A matrix of pairwise correlations that were estimated or set separately often fails the last condition, and the Cholesky factorisation then stops. Three correlations of 0.9, 0.9 and -0.5 among three assets cannot all hold, since two assets that are both strongly correlated with a third must be positively correlated with each other.
Two repairs are used. Eigenvalue clipping replaces the negative eigenvalues by a small positive number, \(\tilde\Sigma = V \max(\Lambda, \epsilon) V^\top\), and rescales to a unit diagonal. It is fast and not the closest valid matrix. The nearest correlation matrix of Higham is the valid matrix closest to the original in the Frobenius norm, found by alternately projecting onto the positive semi-definite matrices and onto the matrices with unit diagonal. Either way, the repair changes the entries, and the size of the change is information about the quality of the input.
Eigenvalues and principal components#
A symmetric matrix has the decomposition \(\Sigma = V \Lambda V^\top\) with orthonormal eigenvectors \(v_k\) and eigenvalues \(\lambda_1 \ge \lambda_2 \ge \dots\). For a covariance matrix of rates, the eigenvectors are the principal components, the independent risk factors, and \(\lambda_k / \sum_j \lambda_j\) is the share of the variance that factor \(k\) explains. For curves, the first three are the level, the slope and the curvature. The sign of an eigenvector is arbitrary, and only its shape is meaningful.
Worked example#
The example solves tridiagonal systems three ways and times them, solves the Hilbert matrix, which is notoriously ill-conditioned, compares the normal equations with QR for a polynomial fit, repairs a correlation matrix that is not positive semi-definite, and finds the principal components of a ten-tenor correlation matrix.
Python code
"""Numerical linear algebra: tridiagonal and dense solves, conditioning, Cholesky of correlation matrices, PCA of a curve."""
import time
import warnings
import numpy as np
from scipy.linalg import LinAlgError, cholesky, eigh, hilbert, solve, solve_banded
warnings.filterwarnings("ignore", category=Warning, module="scipy")
warnings.filterwarnings("ignore", message="Ill-conditioned")
def thomas(lower, diag, upper, rhs):
"""Solve a tridiagonal system in O(n): forward elimination then back substitution."""
n = len(diag)
c, d = np.zeros(n - 1), np.zeros(n)
c[0], d[0] = upper[0] / diag[0], rhs[0] / diag[0]
for i in range(1, n):
denom = diag[i] - lower[i - 1] * c[i - 1]
if i < n - 1:
c[i] = upper[i] / denom
d[i] = (rhs[i] - lower[i - 1] * d[i - 1]) / denom
x = np.zeros(n)
x[-1] = d[-1]
for i in range(n - 2, -1, -1):
x[i] = d[i] - c[i] * x[i + 1]
return x
def nearest_correlation(a, iterations=200):
"""Higham alternating projections onto the positive semi-definite matrices and the unit-diagonal matrices."""
delta = np.zeros_like(a)
y = a.copy()
for _ in range(iterations):
r = y - delta
w, v = eigh(r)
x = (v * np.maximum(w, 0)) @ v.T
delta = x - r
y = x.copy()
np.fill_diagonal(y, 1.0)
return y
if __name__ == "__main__":
print("1. A tridiagonal system, as in an implicit finite-difference step: n unknowns, diagonal 2, off-diagonals -0.5")
print(f" {'n':>6} {'dense LU (ms)':>14} {'banded (ms)':>12} {'Thomas, Python (ms)':>20} {'largest difference':>20}")
rng = np.random.default_rng(1)
for n in (200, 1000, 4000):
lower, upper, diag = np.full(n - 1, -0.5), np.full(n - 1, -0.5), np.full(n, 2.0)
rhs = rng.standard_normal(n)
dense = np.diag(diag) + np.diag(lower, -1) + np.diag(upper, 1)
ab = np.zeros((3, n))
ab[0, 1:], ab[1], ab[2, :-1] = upper, diag, lower
times, results = [], []
for fn in (lambda: solve(dense, rhs), lambda: solve_banded((1, 1), ab, rhs), lambda: thomas(lower, diag, upper, rhs)):
best = 1e9
for _ in range(5):
start = time.perf_counter()
result = fn()
best = min(best, (time.perf_counter() - start) * 1e3)
times.append(best)
results.append(result)
print(f" {n:6d} {times[0]:14.2f} {times[1]:12.3f} {times[2]:20.2f} {max(np.max(np.abs(results[0] - r)) for r in results[1:]):20.1e}")
print("\n2. Conditioning: solve H x = b for the Hilbert matrix with x = 1, in double precision")
print(f" {'n':>3} {'condition number':>18} {'relative error':>16} {'cond x 1.1e-16':>16}")
for n in (4, 6, 8, 10, 12):
h = hilbert(n)
x = solve(h, h @ np.ones(n))
print(f" {n:3d} {np.linalg.cond(h):18.2e} {np.linalg.norm(x - 1) / np.linalg.norm(np.ones(n)):16.2e} {np.linalg.cond(h) * 1.1e-16:16.2e}")
print("\n3. Normal equations against QR for a degree-9 polynomial fit on 30 points in [0, 1], true coefficients 1, 2, ..., 10")
t = np.linspace(0, 1, 30)
a = np.vander(t, 10, increasing=True)
coef = np.arange(1.0, 11.0)
b = a @ coef
print(f" condition number of A {np.linalg.cond(a):.2e}, of A'A {np.linalg.cond(a.T @ a):.2e}")
for name, c in (("Normal equations", solve(a.T @ a, a.T @ b)), ("QR / SVD (lstsq)", np.linalg.lstsq(a, b, rcond=None)[0])):
print(f" {name:<20} largest coefficient error {np.max(np.abs(c - coef)):.2e}")
print("\n4. Cholesky and a correlation matrix that is not positive semi-definite")
bad = np.array([[1.0, 0.9, 0.9], [0.9, 1.0, -0.5], [0.9, -0.5, 1.0]])
print(f" smallest eigenvalue {eigh(bad, eigvals_only=True)[0]:+.4f}")
try:
cholesky(bad, lower=True)
except LinAlgError as error:
print(f" Cholesky fails: {error}")
w, v = eigh(bad)
clipped = (v * np.maximum(w, 1e-8)) @ v.T
d = np.sqrt(np.diag(clipped))
clipped = clipped / np.outer(d, d)
higham = nearest_correlation(bad)
print(f" {'Repair':<28} {'smallest eigenvalue':>20} {'Frobenius distance':>20} {'largest entry change':>22}")
for name, m in (("Clip eigenvalues, rescale", clipped), ("Higham nearest correlation", higham)):
print(f" {name:<28} {eigh(m, eigvals_only=True)[0]:20.2e} {np.linalg.norm(m - bad):20.4f} {np.max(np.abs(m - bad)):22.4f}")
print(" Higham matrix:")
for row in higham:
print(" " + " ".join(f"{e:7.4f}" for e in row))
chol = cholesky(higham + 1e-10 * np.eye(3), lower=True)
z = rng.standard_normal((3, 200_000))
print(f" correlation of 200,000 simulated draws minus the matrix: largest error {np.max(np.abs(np.corrcoef(chol @ z) - higham)):.4f}")
print("\n5. Principal components of a curve: 10 tenors, correlation exp(-0.1 |Ti - Tj|)")
tenors = np.arange(1.0, 11.0)
corr = np.exp(-0.1 * np.abs(tenors[:, None] - tenors[None, :]))
w, v = eigh(corr)
w, v = w[::-1], v[:, ::-1]
print(" share of variance by factor: " + " ".join(f"{s:.1%}" for s in w[:4] / w.sum()))
print(" cumulative: " + " ".join(f"{s:.1%}" for s in np.cumsum(w[:4]) / w.sum()))
for k, name in enumerate(("level", "slope", "curvature")):
vec = v[:, k] * np.sign(v[-1, k] if k else v[0, k])
print(f" factor {k + 1} ({name:<9}) loadings at 1, 5, 10 years: {vec[0]:+.3f} {vec[4]:+.3f} {vec[9]:+.3f}")
The output is:
1. A tridiagonal system, as in an implicit finite-difference step: n unknowns, diagonal 2, off-diagonals -0.5
n dense LU (ms) banded (ms) Thomas, Python (ms) largest difference
200 0.11 0.019 0.24 2.2e-16
1000 1.14 0.035 1.21 4.4e-16
4000 20.44 0.102 5.04 4.4e-16
2. Conditioning: solve H x = b for the Hilbert matrix with x = 1, in double precision
n condition number relative error cond x 1.1e-16
4 1.55e+04 2.51e-13 1.71e-12
6 1.50e+07 1.86e-11 1.64e-09
8 1.53e+10 5.62e-08 1.68e-06
10 1.60e+13 6.49e-05 1.76e-03
12 1.64e+16 2.00e-01 1.81e+00
3. Normal equations against QR for a degree-9 polynomial fit on 30 points in [0, 1], true coefficients 1, 2, ..., 10
condition number of A 3.52e+06, of A'A 1.24e+13
Normal equations largest coefficient error 6.28e-04
QR / SVD (lstsq) largest coefficient error 8.34e-10
4. Cholesky and a correlation matrix that is not positive semi-definite
smallest eigenvalue -0.5471
Cholesky fails: 3-th leading minor of the array is not positive definite
Repair smallest eigenvalue Frobenius distance largest entry change
Clip eigenvalues, rescale 8.43e-09 0.6769 0.3040
Higham nearest correlation -5.75e-28 0.6750 0.2918
Higham matrix:
1.0000 0.6082 0.6082
0.6082 1.0000 -0.2601
0.6082 -0.2601 1.0000
correlation of 200,000 simulated draws minus the matrix: largest error 0.0012
5. Principal components of a curve: 10 tenors, correlation exp(-0.1 |Ti - Tj|)
share of variance by factor: 74.1% 14.0% 4.7% 2.3%
cumulative: 74.1% 88.1% 92.8% 95.2%
factor 1 (level ) loadings at 1, 5, 10 years: +0.282 +0.338 +0.282
factor 2 (slope ) loadings at 1, 5, 10 years: -0.418 -0.076 +0.418
factor 3 (curvature) loadings at 1, 5, 10 years: +0.430 -0.414 +0.430
Reading the output:
The structure of the matrix decides the cost. All three solvers agree to 4e-16. The dense solve takes 20 ms at 4,000 unknowns, 18 times its time at 1,000, while the banded solver takes 0.10 ms and the Thomas algorithm, written as a Python loop, 5 ms, four times its time at 1,000. Timings are indicative. A finite-difference grid is solved by the banded routine and not by a general one.
Digits are lost to the condition number. The relative error of the Hilbert solution is 2.5e-13 at \(n = 4\), \(\kappa = 1.6 \times 10^4\), and 6.5e-5 at \(n = 10\), \(\kappa = 1.6 \times 10^{13}\). At \(n = 12\), \(\kappa \varepsilon\) is 1.8, no digit is guaranteed, and the solution is wrong by 20%. The product \(\kappa \varepsilon\) is an upper bound, and the error is below it every time.
The normal equations lose twice the digits. The polynomial design matrix has \(\kappa = 3.5 \times 10^6\) and \(A^\top A\) has \(1.2 \times 10^{13}\). The coefficients from the normal equations are wrong by 6.3e-4 and those from QR by 8.3e-10, a factor of about 750,000.
An invalid correlation matrix is common and it can be repaired. The three correlations of 0.9, 0.9 and -0.5 give an eigenvalue of -0.547, and Cholesky fails at the third row. Clipping gives a valid matrix at a Frobenius distance of 0.677, and Higham’s matrix is closer, 0.675, by construction. The repair is not small: the two 0.9 correlations fall to 0.61, and the largest entry changes by 0.29. A repair this large says that the input is inconsistent. The simulated correlation of the repaired matrix agrees to 0.0012, which is the sampling error for 200,000 draws.
A few factors explain a curve. The level explains 74.1% of the variance of the ten-tenor curve, the slope 14.0% and the curvature 4.7%, so three factors explain 92.8%. The level loads with the same sign at all tenors, the slope changes sign from -0.418 at one year to +0.418 at ten, and the curvature is positive at both ends and negative at five years.
A valuation control view#
Check the condition number when a system is solved: a number near \(10^{16}\) means that the answer is noise. A calibration or a regression with a large condition number is not identified, whatever the fit looks like.
Do not solve least-squares problems through the normal equations when the design is ill-conditioned: use QR or the SVD. It costs little, and gives back the digits that the squaring loses.
Test every correlation matrix for positive semi-definiteness before it is used: check the smallest eigenvalue. A matrix assembled entry by entry, from different sources or with some entries overridden, often fails.
Record the repair and its size: a Frobenius distance or a largest entry change of 0.3 is not a rounding repair, and the effect on the price of a correlation-sensitive product should be measured. See Interest Rate Correlation.
Use the structure: a banded solver for a grid, Cholesky for a positive definite matrix. A general solver on a large banded system works, and slowly.
Next, Root Finding: Implied Volatility covers the problem of solving a single non-linear equation, and the most common case of it in finance, the implied volatility.