Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Differentiation

Open in Colab

Numerical differentiation

Finite differences

The simplest way to numerically approximate a derivative is by approximating the above limit. This is called a “finite difference method”.

The three simplest finite methods are the forward difference

f′(x)≈f(x+h)−f(x)hf'(x) \approx \frac{f(x+h) - f(x)}{h}

the backwards difference

f′(x)≈f(x)−f(x−h)hf'(x) \approx \frac{f(x) - f(x-h)}{h}

and the central difference

f′(x)≈f(x+h)−f(x−h)2hf'(x) \approx \frac{f(x+h) - f(x-h)}{2h}

We test these differences on the function

g(x)=x(x−1)e−xg(x) = x(x-1)e^{-x}

its derivative is

g′(x)=[−x(x−1)+(x−1)+x]e−xg'(x) = \left[-x(x-1) + (x-1) + x \right]e^{-x}

Let’s look at the errors at h=1e-5

We see the central difference gives a better approximation. This is due to the fact that when ff is smooth, we have that

f′(x)=f(x+h)−f(x)h+O(h)f'(x) = \frac{f(x+h) - f(x)}{h} + O(h)
f′(x)≈f(x)−f(x−h)h+O(h)f'(x) \approx \frac{f(x) - f(x-h)}{h} + O(h)
f′(x)≈f(x+h)−f(x−h)2h+O(h2)f'(x) \approx \frac{f(x+h) - f(x-h)}{2h} + O(h^2)

When h becomes too small (around 1e-6 for central diff and 1e-10 for forward/backward diff), the error grows linearly again. This is because floating point error matters more both on the numerator and denominator. You may want to set your default value of h to be 1e-6to balance accuracy and floating number error.

Numerical Differentiation on a Grid

Suppose we have a function on a grid

g(x)=sin⁡(3x)e−x2g(x) = \sin(3x) e^{-x^2}

with derivative

g′(x)=3cos⁡(3x)e−x2−2xsin⁡(3x)e−x2g'(x) = 3\cos(3x)e^{-x^2} - 2x\sin(3x)e^{-x^2}

What if we want to evaluate the derivative at each point on the grid?

numpy provides a function to efficiently compute this using differences: diff. This is equivalent to

np.array([gx[i+1] - gx[i] for i in range(len(gx) - 1)

In order to approximate the derivative using a forward difference, we simply divide by hh. Note that we can’t use the forward difference to approximate value at the last grid point.

Let {x0,x1,…xn−1}\{ x_0, x_1, \dots x_{n-1}\} be the grid of points with mesh ∣xi+1−xi∣=h|x_{i+1} - x_{i}| = h. The continuous function ff defined on the grid is an nn-vector

fvec=(f(x0),…f(xn−1))⊤.f_{\mathrm {vec}} = \left( f(x_0), \dots f(x_{n-1}) \right)^\top.

The forward differnce operator can be expressed as applying the sparse matrix

A=1h(−110−11−11⋱0…0)A = \frac1h \begin{pmatrix} -1 & 1 &&0 \\ & -1 & 1 &\\ & &-1 &1 & \\ &&& \ddots \\ 0 & \dots && & 0\end{pmatrix}

which could be implemented using the sparse matrix classes from earlier lectures. So that AfvecAf_{\mathrm {vec}} is the finite difference on ff.

Note that difference schemes can’t compute the derivate at the two end points.

One approach is to use

* Central difference in the interior
* Forward difference at the left
* Back difference at the right

This can be expressed as applying the sparse matrix

A=1h(−11⋯0−1/201/2−1/201/20⋱−11)A = \frac1h \begin{pmatrix} -1 & 1 & \cdots& &0 \\ -1/2& 0 & 1/2 &\\ & -1/2 & 0 & 1/2 \\ 0&&& \ddots \\ &&&-1 & 1 \end{pmatrix}

There are also more complicated difference formulas. We could, for example, achieve more accuracy on the right using the so-called BDF2 formula

f′(x)≈f(x)−43f(x−h)+13f(x−2h)23h+O(h2)f'(x) \approx \frac{f(x) - \frac43 f(x-h) + \frac13 f(x-2h)}{\frac23 h}+O(h^2)

Finite difference schemes are designed by choosing a “stencil” (the required function values) and then finding the coefficients that work through Taylor series calculations.

Higher order derivatives

For simplicity, we’ll use the square matrix above

Because differentiation is linear, we can compute second derivatives by repeatedly applying the above derivative operator

What we are seeing here is that repeatedly applying the central difference gives

f′′(x)≈f(x+2h)−2f(x)+f(x−2h)4h2f''(x)\approx \frac{f(x+2h)-2 f(x) + f(x-2h)}{4h^2}

If we applied forward and then backwards difference, we would instead find that

f′′(x)≈f(x+h)−2f(x)+f(x−h)h2f''(x)\approx \frac{f(x+h)-2 f(x) + f(x-h)}{h^2}

Optional: Higher dimensional grids

Recall that a derivative measures the rate of change of a function

dfdx=lim⁡h→0f(x+h)−f(x)h\frac{df}{dx} = \lim_{h\to 0} \frac{f(x+h)-f(x)}{h}

For a functions of multiple variables we also have the partial derivative

∂f∂xi=lim⁡h→0f(x+hei)−f(x)h\frac{\partial f}{\partial x_i} = \lim_{h\to 0} \frac{f(x+h e_i)-f(x)}{h}

the gradient

∇f=[∂f∂x1,∂f∂x2,…]T\nabla f = \begin{bmatrix} \frac{\partial f}{\partial x_1} ,\frac{\partial f}{\partial x_2},\ldots\end{bmatrix}^T

and the Hessian

H=[∂2f∂xi∂xj]i,jH = \left[\frac{\partial^2 f}{\partial x_i\partial x_j} \right]_{i,j}

We will create an operator that will act as a derivative on the function defined on R2\mathbb R^2:

g(x,y)=sin⁡(x)+cos⁡(y).g(x,y) = \sin(x) + \cos(y).

We will treat function evaluated at the mesh grid as a vector

A naive way of building the finite difference matrix is to identify which element in the finite difference scheme corresponds to the coordinates in x_coord and y_coord.

Recall that numpy arrays are row-major by default. This means that if we want to compute derivatives in the xx direction, we can simply create a block matrix with a derivative operator for each block in a contiguous row.

scipy.sparse.kron is a very useful function to create such a sparse matrix.

The Kronecker product A⊗BA\otimes B is the block matrix whose (i,j)(i,j) block is aijBa_{ij}B. If DD is the 1-dimensional difference matrix from before, then

  • Dx=I⊗DD_x = I\otimes D is block diagonal. It applies DD to each row of the grid, i.e. to each contiguous block of the vector.

  • Dy=D⊗ID_y = D\otimes I takes differences between rows of the grid, i.e. between entries that are nxn_x apart in the vector.

Here are the sparsity patterns on a 4×44\times 4 grid

Now we build the operators for our 100×100100\times 100 grid. Note that meshgrid puts xx along the columns and yy along the rows.

Applying an operator to the vector and reshaping the result gives the partial derivative on the grid

Since g=sin⁡x+cos⁡yg = \sin x + \cos y, we know ∂xg=cos⁡x\partial_x g = \cos x and ∂yg=−sin⁡y\partial_y g = -\sin y. As in one dimension, the error is O(h2)O(h^2) in the interior and O(h)O(h) on the boundary, where we fall back to one-sided differences.

numpy also provides np.gradient, which uses the same scheme (central differences in the interior, one-sided differences at the ends) along every axis of an array. It returns one array per axis, so for our grid the first output is the yy-derivative.

With DxD_x and DyD_y we can assemble these as sparse operators on the flattened grid function. With N=nxnyN = n_x n_y grid points, the gradient stacks the two partials into a 2N×N2N\times N matrix

∇≈[DxDy]\nabla \approx \begin{bmatrix} D_x \\ D_y \end{bmatrix}

and the entries of the Hessian are approximated by DxDxD_x D_x, DxDyD_x D_y, DyDxD_y D_x and DyDyD_y D_y. Because DxD_x and DyD_y act on different indices,

(I⊗D)(D⊗I)=D⊗D=(D⊗I)(I⊗D)(I\otimes D)(D\otimes I) = D\otimes D = (D\otimes I)(I\otimes D)

so the discrete mixed partials are equal, just like the continuous ones.

The Laplacian is the trace of the Hessian

Δf=∂2f∂x2+∂2f∂y2\Delta f = \frac{\partial^2 f}{\partial x^2} + \frac{\partial^2 f}{\partial y^2}

For our function, Δg=−sin⁡x−cos⁡y=−g\Delta g = -\sin x - \cos y = -g.