import numpy as np
from numpy import exp
import scipy.sparse as sparse
import matplotlib.pyplot as pltNumerical 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
the backwards difference
and the central difference
def forward_diff(f,x,h=1e-8):
return (f(x+h)-f(x))/h
def backward_diff(f,x,h=1e-8):
return (f(x)-f(x-h))/h
def central_diff(f,x,h=1e-8):
return (f(x+h)-f(x-h))/h/2.
g = lambda x: exp(-x)*x*(x-1)
gp = lambda x: exp(-x)*(-x*(x-1)+(x-1)+x)
x0 = 0.2
print("True value : {}".format(gp(x0)))
for diff in [forward_diff, backward_diff, central_diff]:
print("{} : {}".format(diff.__name__, diff(g,x0,1e-3)))hs = np.logspace(0, -12, 100)
err_f = np.zeros(len(hs))
err_b = np.zeros(len(hs))
err_c = np.zeros(len(hs))
for i in range(len(hs)):
err_f[i] = abs(forward_diff(g,x0,hs[i]) - gp(x0))
err_b[i] = abs(backward_diff(g,x0,hs[i]) - gp(x0))
err_c[i] = abs(central_diff(g,x0,hs[i]) - gp(x0))
plt.loglog(hs,err_f, label='forward diff')
plt.loglog(hs,err_b, label='backwawrd diff')
plt.loglog(hs,err_c, label='central diff')
plt.xlabel('h')
plt.ylabel('error')
plt.legend()
plt.show()Let’s look at the errors at h=1e-5
for diff in [forward_diff, backward_diff, central_diff]:
print("Error in {} : {}".format(diff.__name__, abs(diff(g,x0,1e-5)-gp(x0))))We see the central difference gives a better approximation. This is due to the fact that when is smooth, we have that
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.
g = lambda x: np.sin(3*x)*exp(-x*x)
gp = lambda x: 3 * np.cos(3*x)*exp(-x*x) - 2*x*np.sin(3*x)*exp(-x*x)
a, b = -5, 5
n = 100
xs = np.linspace(a, b, n) # start from a, end at b, n points
h = (b-a) / (n-1)
gx = g(xs)
gpx = gp(xs)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 . Note that we can’t use the forward difference to approximate value at the last grid point.
import matplotlib.pyplot as plt
g1 = np.diff(gx)/h
plt.plot(xs, gx, label= 'g')
plt.plot(xs, gpx, label= "g' analytic")
plt.plot(xs[:-1], g1, label="g' finite diff") # plot must exclude end point
plt.legend()
plt.show()Let be the grid of points with mesh . The continuous function defined on the grid is an -vector
The forward differnce operator can be expressed as applying the sparse matrix
which could be implemented using the sparse matrix classes from earlier lectures. So that is the finite difference on .
import scipy.sparse as sparse# create the forward difference matrix A, equivalent to np.diff
def forward_diff_matrix(n):
data = []
i = []
j = []
for k in range(n - 1):
i.append(k)
j.append(k)
data.append(-1)
i.append(k)
j.append(k+1)
data.append(1)
# we'll just set the last entry to 0 to have a square matrix
return sparse.coo_matrix((data,(i,j)),shape=(n,n)).tocsr()
D = forward_diff_matrix(len(gx))/h
D.toarray()gx1 = D @ gx
plt.plot(xs, gpx, label= "g' analytic")
plt.plot(xs, gx1, label= "g' finite diff")
plt.legend()
plt.show()
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 rightThis can be expressed as applying the sparse matrix
# create the forward difference matrix A, equivalent to np.diff
def diff_matrix(n):
data = []
i = []
j = []
# forward on the left
i.append(0)
j.append(0)
data.append(-1)
i.append(0)
j.append(1)
data.append(1)
# central in the middle
for k in range(1,n - 1):
i.append(k)
j.append(k-1)
data.append(-0.5)
i.append(k)
j.append(k+1)
data.append(0.5)
# backward on the right
# forward on the left
i.append(n-1)
j.append(n-1)
data.append(1)
i.append(n-1)
j.append(n-2)
data.append(-1)
return sparse.coo_matrix((data,(i,j)),shape=(n,n)).tocsr()
D = diff_matrix(len(gx))/h
D.toarray()gx1 = D @ gx
plt.plot(xs,gx1)
plt.show()There are also more complicated difference formulas. We could, for example, achieve more accuracy on the right using the so-called BDF2 formula
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
D1 = diff_matrix(len(gx))
plt.spy(D1)Because differentiation is linear, we can compute second derivatives by repeatedly applying the above derivative operator
# second derivative
D2 = D1 @ D1# third derivative
D3 = D1 @ D2gx2 = D2 @ gx
plt.plot(xs,gx2)
plt.show()D2[:8,:8].todense()What we are seeing here is that repeatedly applying the central difference gives
If we applied forward and then backwards difference, we would instead find that
Optional: Higher dimensional grids¶
Recall that a derivative measures the rate of change of a function
For a functions of multiple variables we also have the partial derivative
the gradient
and the Hessian
We will create an operator that will act as a derivative on the function defined on :
xx, yy = np.meshgrid(np.linspace(-10,10,100),np.linspace(-10,10,100))
g_func = lambda x, y: np.sin(x) + np.cos(y)
g2d = g_func(xx, yy)
plt.imshow(g2d)
plt.show()We will treat function evaluated at the mesh grid as a vector
# turn 2-dimensional function to a vector
g = g2d.flatten()
# the coordinate of i-th element in g is provided by (x_coord[i], y_coord[i])
x_coord = xx.flatten()
y_coord = yy.flatten()
i = 200
print(g[i] - g_func(x_coord[i], y_coord[i]))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 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 is the block matrix whose block is . If is the 1-dimensional difference matrix from before, then
is block diagonal. It applies to each row of the grid, i.e. to each contiguous block of the vector.
takes differences between rows of the grid, i.e. between entries that are apart in the vector.
Here are the sparsity patterns on a grid
fig, axs = plt.subplots(1, 2, figsize=(8, 4))
axs[0].spy(sparse.kron(sparse.eye(4), diff_matrix(4)))
axs[0].set_title(r'$I \otimes D$')
axs[1].spy(sparse.kron(diff_matrix(4), sparse.eye(4)))
axs[1].set_title(r'$D \otimes I$')
plt.show()Now we build the operators for our grid. Note that meshgrid puts along the columns and along the rows.
ny, nx = g2d.shape
hx = xx[0, 1] - xx[0, 0] # x changes along each row
hy = yy[1, 0] - yy[0, 0] # y changes down each column
Dx = sparse.kron(sparse.eye(ny), diff_matrix(nx)).tocsr() / hx
Dy = sparse.kron(diff_matrix(ny), sparse.eye(nx)).tocsr() / hyApplying an operator to the vector and reshaping the result gives the partial derivative on the grid
dgdx = (Dx @ g).reshape(g2d.shape)
dgdy = (Dy @ g).reshape(g2d.shape)
fig, axs = plt.subplots(1, 2, figsize=(10, 4))
axs[0].imshow(dgdx)
axs[0].set_title(r'$\partial g / \partial x$')
axs[1].imshow(dgdy)
axs[1].set_title(r'$\partial g / \partial y$')
plt.show()Since , we know and . As in one dimension, the error is in the interior and on the boundary, where we fall back to one-sided differences.
errx = np.abs(dgdx - np.cos(xx))
erry = np.abs(dgdy + np.sin(yy))
print("max error in x :", errx.max())
print("max error in x (interior) :", errx[:, 1:-1].max())
print("max error in y :", erry.max())
print("max error in y (interior) :", erry[1:-1, :].max())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 -derivative.
dgdy_np, dgdx_np = np.gradient(g2d, hy, hx)
print(np.allclose(dgdx, dgdx_np), np.allclose(dgdy, dgdy_np))With and we can assemble these as sparse operators on the flattened grid function. With grid points, the gradient stacks the two partials into a matrix
and the entries of the Hessian are approximated by , , and . Because and act on different indices,
so the discrete mixed partials are equal, just like the continuous ones.
grad = sparse.vstack([Dx, Dy])
print(grad.shape)
Dxx = Dx @ Dx
Dxy = Dx @ Dy
Dyy = Dy @ Dy
print("max |DxDy - DyDx| :", abs(Dx @ Dy - Dy @ Dx).max())L = Dxx + Dyy
Lg = (L @ g).reshape(g2d.shape)
err = np.abs(Lg + g2d)
print("max error :", err.max())
print("max interior error :", err[2:-2, 2:-2].max())
fig, axs = plt.subplots(1, 3, figsize=(12,3))
axs[0].imshow(Lg)
axs[0].set_title(r'$\Delta g$')
axs[1].imshow(g2d)
axs[1].set_title(r'$g$')
im = axs[2].imshow(err)
axs[2].set_title(r'Error')
fig.colorbar(im, ax=axs[2])
plt.show()