Solve a tridiagonal system in linear time with the Thomas algorithm

Splines, implicit time steps and 1D physics produce tridiagonal systems. A general solver costs n cubed; the Thomas algorithm does it in n steps.

Write solve_tridiagonal(a, b, c, d). b is the main diagonal (length n), a is the sub-diagonal (length n - 1), c is the super-diagonal (length n - 1), d is the right-hand side. Return x with A x = d. Assume no pivoting is needed.

Signaturedef solve_tridiagonal(a, b, c, d)

Example

a = [1], b = [2, 2], c = [1], d = [3, 3] gives [1, 1].

Understand the idea

A tridiagonal system has non-zeros only on the main diagonal and the two next to it. A general solver wastes time on all the zeros; the Thomas algorithm solves it in two quick passes, forward elimination and back substitution. Worked example: a = [1, 1], b = [4, 4, 4], c = [1, 1], d = [5, 6, 5]. Forward: c'0 = 1 / 4 = 0.25, d'0 = 5 / 4 = 1.25. Row 1: m = 4 - 1 * 0.25 = 3.75, c'1 = 1 / 3.75 = 0.2667, d'1 = (6 - 1.25) / 3.75 = 1.2667. Row 2: m = 4 - 0.2667 = 3.7333, d'2 = (5 - 1.2667) / 3.7333 = 1. Back: x2 = 1, x1 = 1.2667 - 0.2667 * 1 = 1, x0 = 1.25 - 0.25 * 1 = 1. So x = [1, 1, 1]. Rule: forward, m_i = b_i - a_(i-1) * c'_(i-1), c'_i = c_i / m_i, d'_i = (d_i - a_(i-1) * d'_(i-1)) / m_i; backward, x_last = d'_last, x_i = d'_i - c'_i * x_(i+1). Always use the updated d', not the original d. Used in cubic splines and implicit time stepping.

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

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

  • Sample 1: examplesolve_tridiagonal([1], [2, 2], [1], [3, 3])
  • Sample 2: matches dense solvesolve_tridiagonal(_a, _b, _c, _d)
  • Test 3: singlesolve_tridiagonal([], [4], [], [2])