One Triangle, Used Twice

Matrix DecompositionsMedium+20 XP+20

One Triangle, Used Twice

LU decomposition splits a matrix into two different triangles. Some matrices allow a neater split that uses one triangle twice:

A=L LTA = L\,L^{\mathsf T}A=LLT

Here LLL is lower triangular (zeros above its diagonal) with positive numbers on its diagonal, and LTL^{\mathsf T}LT is its transpose. This is the Cholesky decomposition. It stores one triangle instead of two and takes about half the work of LU, so libraries reach for it first whenever a matrix qualifies.

Finding LLL. Entry (i,j)(i, j)(i,j) of LLTLL^{\mathsf T}LLT is the dot product of row iii of LLL with row jjj of LLL. Matching those dot products to the entries of AAA, one column of LLL at a time from left to right, gives

Ljj=Ajj−∑k<jLjk2Lij=Aij−∑k<jLik LjkLjjfor i>jL_{jj} = \sqrt{A_{jj} - \sum_{k<j} L_{jk}^{2}} \qquad\qquad L_{ij} = \frac{A_{ij} - \sum_{k<j} L_{ik}\,L_{jk}}{L_{jj}} \quad \text{for } i > jLjj​=Ajj​−k<j∑​Ljk2​​Lij​=Ljj​Aij​−∑k<j​Lik​Ljk​​for i>j

For example, A=[9665]A = \begin{bmatrix} 9 & 6 \\ 6 & 5 \end{bmatrix}A=[96​65​] gives L00=9=3L_{00} = \sqrt{9} = 3L00​=9​=3, then L10=6/3=2L_{10} = 6/3 = 2L10​=6/3=2, then L11=5−22=1L_{11} = \sqrt{5 - 2^2} = 1L11​=5−22​=1. Check: [3021][3201]=[9665]\begin{bmatrix} 3 & 0 \\ 2 & 1 \end{bmatrix}\begin{bmatrix} 3 & 2 \\ 0 & 1 \end{bmatrix} = \begin{bmatrix} 9 & 6 \\ 6 & 5 \end{bmatrix}[32​01​][30​21​]=[96​65​].

When there is no such LLL. Not every matrix has a Cholesky decomposition. Two things rule it out:

  • AAA is not symmetric, meaning it differs from its own transpose: Aij≠AjiA_{ij} \ne A_{ji}Aij​=Aji​ for some i,ji, ji,j. Every LLTLL^{\mathsf T}LLT is symmetric, so no LLL can rebuild such an AAA.
  • A number under one of the square roots comes out zero or negative. Symmetric matrices for which this never happens are called positive-definite, and running the formulas is how you find out.

Task: write cholesky(A), where A is a square matrix given as a list of lists.

  • If A is not exactly symmetric, return None.
  • If any number under a square root is ≤10−10\le 10^{-10}≤10−10, return None.
  • Otherwise return LLL as a list of lists of floats, including the 0.0 entries above the diagonal, with every entry rounded to 4 decimal places. Round only the finished answer; the formulas use the unrounded values.

Examples

A = [[4, 2], [2, 10]]
returns [[2.0, 0.0], [1.0, 3.0]]
A = [[2, -1, 0], [-1, 2, -1], [0, -1, 2]]
returns [[1.4142, 0.0, 0.0], [-0.7071, 1.2247, 0.0], [0.0, -0.8165, 1.1547]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run