32. 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.
def solve_tridiagonal(a, b, c, d)Example 1
Input: a = [1], b = [2, 2], c = [1], d = [3, 3]
Output: [1, 1]
Example 2
Input: a = [0.740498, -0.426366, 0.206296, 0.555068], b = [4.026588, 4.437248, 4.484944, 4.065154, 4.005626], c = [0.432149, 0.83076, 0.720787, 0.836475], d = [2.522327, 0.826218, 0.277781, -0.657431, 1.392469]
Output: [0.619691, 0.06268, 0.107384, -0.24571, 0.381677]
Example 3
Input: a = [], b = [4], c = [], d = [2]
Output: [0.5]
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
Hint 1
Forward sweep: c'[i] = c[i] / (b[i] - a[i-1] c'[i-1]) and the same denominator for d'.
Hint 2
Then back-substitute from the end.
Common mistakes
- The buggy version uses the original right-hand side instead of the updated one, so eliminated terms come back.
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.
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].
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.