Write a Cholesky factorisation and use it to solve a system

Gaussian processes and Newton steps solve systems with symmetric positive definite matrices. Cholesky, A = L L.T, is twice as fast as LU and numerically stable.

Write cholesky_solve(A, b). Build the lower triangular L column by column yourself (do not call np.linalg.cholesky or solve), then solve L y = b by forward substitution and L.T x = y by back substitution. Return (L, x).

Signaturedef cholesky_solve(A, b)

Example

A = [[4, 2], [2, 3]], b = [2, 1] gives L = [[2, 0], [1, sqrt 2]] and x = [0.5, 0].

Understand the idea

A symmetric positive definite matrix can be written as A = L L^T with L lower triangular. Solving A x = b then becomes two easy triangular solves: L y = b going down, then L^T x = y going up. Worked example: A = [[9, 3], [3, 5]], b = [3, 3]. L00 = sqrt(9) = 3. L10 = 3 / 3 = 1. L11 = sqrt(5 - 1^2) = 2. So L = [[3, 0], [1, 2]]. Forward: y0 = 3 / 3 = 1, y1 = (3 - 1 * 1) / 2 = 1. Backward with L^T = [[3, 1], [0, 2]]: x1 = 1 / 2 = 0.5, x0 = (1 - 1 * 0.5) / 3 = 0.1667. Rule: L_jj = sqrt(A_jj - sum over k < j of L_jk^2); for i > j, L_ij = (A_ij - sum over k < j of L_ik * L_jk) / L_jj. In back substitution, row i of L^T is column i of L, so read entries below the diagonal of L. It is about twice as fast as LU and is used in Gaussian processes and Newton steps.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplecholesky_solve([[4, 2], [2, 3]], [2, 1])
  • Sample 2: random spdcholesky_solve(_A, _b)
  • Test 3: identitycholesky_solve(np.eye(3), [1, 2, 3])