Solving a Tridiagonal System#
We want to solve a tridiagonal system of the form:
Here, the main diagonal is represented by \(b_i\), which runs from \(i = 0, \ldots, N-1\). The two off diagonals have one fewer entries.
We can solve this just using Gaussian elimination, as before, but we won’t need to pivot, since the structure is the same on all rows. The result is the tridiagonal matrix solver. Notice that we only need to update 2 elements in each row instead of \(N\), so by taking advantage of this pattern, this solver will be much faster than the full Gaussian elimination.
Solving in python#
In python, we can use linalg.solve_banded
. This works
by packed the diagonals into a 2D array, as shown on the pages there.
Solving in C++#
For C++, I’ve written a header-only set of functions that take vectors of length \(N\) for the three diagonals and the righthand side and return \(x\). You can find these here: zingale/computational_astrophysics
You can run the test by compiling as:
g++ -I. -o tridiag tridiag.cpp