Finite Difference Matrix
Many matrices in scientific computing contain mostly zeros, particularly those arising
from the discretistaion of partial differential equations (PDEs). Here we will construct
a sparse matrix using scipy.sparse
that is derived from the finite difference
discretistaion of the Poisson equation. In 1D, Poisson equation is
uxx=f(x) for 0≤x≤1
The central FD approximation of uxx is:
uxx≈h2u(x+h)−2u(x)+u(x−h)
We will discretise uxx=0 at N regular points along x from 0 to 1, given by
x1, x2:
+
0 x_1 x_2 ... x_N 1
Using this set of point and the discretised equation, this gives a set of N equations
at each interior point on the domain:
h2vi+1−2vi+vi−1=f(xi) for i=1...N
where vi≈u(xi).
To solve these equations we will need additional equations at x=0 and x=1, known as
the boundary conditions. For this example we will use u(x)=g(x) at x=0 and x=1
(also known as a non-homogenous Dirichlet bc), so that v0=g(0), and vN+1=g(1), and the equation at x1 becomes:
h2vi+1−2vi+g(0)=f(xi)
and the equation at xN becomes:
h2g(1)−2vi+vi−1=f(xi)
We can therefore represent the final N equations in matrix form like so:
h21⎣⎢⎢⎢⎢⎢⎡−211−2⋱1⋱1⋱−211−2⎦⎥⎥⎥⎥⎥⎤⎣⎢⎢⎢⎢⎢⎢⎡v1v2⋮vN−1vN⎦⎥⎥⎥⎥⎥⎥⎤=⎣⎢⎢⎢⎢⎢⎢⎡f(x1)f(x2)⋮f(xN−1)f(xN)⎦⎥⎥⎥⎥⎥⎥⎤−h21⎣⎢⎢⎢⎢⎢⎢⎡g(0)0⋮0g(1)⎦⎥⎥⎥⎥⎥⎥⎤
The relevant sparse matrix here is A, given by
A=⎣⎢⎢⎢⎢⎢⎡−211−2⋱1⋱1⋱−211−2⎦⎥⎥⎥⎥⎥⎤
As you can see, the number of non-zero elements grows linearly with the size N, so a
sparse matrix format is much preferred over a dense matrix holding all N2 elements!
Additional Reading
For more on the Finite Difference Method for solving PDEs:
K. W. Morton and D. F. Mayers. Numerical Solution of Partial Differential Equations: An
Introduction. Cambridge University Press, 2005.