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.

 Open In Colab

Evenly Spaced Data and Boundaries

As long as this data is evenly spaced with step size hh, we can use finite difference directly.

BUT: Be aware of the boundaries! The central difference requires points on both sides of xix_i, which are not available at x0x_0 and xNx_N.

Say we have data for a function y(x)y(x) that looks like a parabola measured at 10 points in the range [a,b][a,b]:

Finite difference parabola data

Boundary Differentiation: np.gradient (edge_order=1)

If we just applied central difference to this function, we would encounter problems at the endpoints.

The numpy function gradient identifies the endpoints and uses first-order forward / backward differences by default (edge_order=1):

Higher-Order Boundary Correction (edge_order=2)

This looks good in the middle, but the ends are funny... What do you think?

Bingo! Using the higher order edge cases (edge_order=2) solved the problem!

Note, this is the foundation of the finite difference method for solving differential equations.

Unevenly Spaced Data and Lagrange Differentiation

When data is unevenly spaced we can always do first-order forward / backward difference (but not central difference. Why?!?). If we want higher order, we generally have to resort to a local polynomial fitting.

Recall quadratic Lagrange interpolation through three points (xi−1,xi,xi+1)(x_{i-1}, x_i, x_{i+1}). Taking its analytic derivative yields:

f′(x)=f(xi−1)2x−xi−xi+1(xi−1−xi)(xi−1−xi+1)+f(xi)2x−xi−1−xi+1(xi−xi−1)(xi−xi+1)+f(xi+1)2x−xi−1−xi(xi+1−xi−1)(xi+1−xi)f'(x) = f(x_{i-1}) \frac{2x - x_i-x_{i+1}}{(x_{i-1}-x_i) (x_{i-1}-x_{i+1})} + f(x_{i}) \frac{2x - x_{i-1}-x_{i+1}}{(x_{i}-x_{i-1}) (x_{i}-x_{i+1})} + f(x_{i+1}) \frac{2x - x_{i-1}-x_{i}}{(x_{i+1}-x_{i-1}) (x_{i+1}-x_{i})}

which is of comparable accuracy to the central difference and recovers it if the points are equally spaced.