Exercise: Differentiation matrix

Task: Make an $(n-1) \times n$ matrix $D$ with the property that when it is applied to a vector $f \in \mathbb{R}^n$ we get $Df \in \mathbb{R}^{n-1}$ whose entries are $$ [D f]_i = f_{i+1} - f_{i}, \qquad i=0, 1, \ldots, n-1. $$ Use the diag facility of numpy to make D fast. Put $x_j = j h$ for some positive grid spacing $h$. If $f_j$ equals $f(x_j)$ for some differentiable function $f$, then $h^{-1} Df$ produces approximations to the derivative of $f$, so we shall call $h^{-1}D$ the differentiation matrix.

In [1]:
import numpy as np
from numpy import diag
  • Apply $D$ to obtain an approximation of the derivative of $f(x) = \sin(x)$, plot the result, and verify that you get what you expect.

  • Apply $D$ to obtain an approximation of the derivative of $f(x) = x^2 + 2\sin(10 x)$ for a thousand or more equally spaced values of $x$. Plot the result. Experiment with what happens if you add the averaging operator from the previous exercise into the mix.

Optional Extra Task: Install scipy if you don't have it already. Then make D as a sparse matrix (that doesn't store zeros) using the following facility in scipy.sparse module:

In [2]:
from scipy.sparse import diags

Apply the sparse differentiation matrix to the functions described above and note if there are any performance gains.