import numpy as np
import plotly.graph_objects as goEvenly Spaced Data and Boundaries¶
As long as this data is evenly spaced with step size , we can use finite difference directly.
BUT: Be aware of the boundaries! The central difference requires points on both sides of , which are not available at and .
Say we have data for a function that looks like a parabola measured at 10 points in the range :

x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
y = np.array([0.5, 1.48765432, 2.22839506, 2.72222222, 2.9691358, 2.9691358,
2.72222222, 2.22839506, 1.48765432, 0.5])
fig = go.Figure()
fig.add_trace(go.Scatter(x=x, y=y, mode="lines+markers", name="Measured Parabola"))
fig.update_layout(title="Discretized Parabola Data", xaxis_title="x", yaxis_title="y", height=400)
fig.show()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):
dy = np.gradient(y, x)
fig = go.Figure()
fig.add_trace(go.Scatter(x=x, y=dy, mode="lines+markers", name="dy/dx (edge_order=1)"))
fig.update_layout(title="Numerical Derivative: dy vs x (edge_order=1)", xaxis_title="x", yaxis_title="dy", height=400)
fig.show()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.
dy2 = np.gradient(y, x, edge_order=2)
fig = go.Figure()
fig.add_trace(go.Scatter(x=x, y=dy, mode="lines+markers", name="edge_order=1"))
fig.add_trace(go.Scatter(x=x, y=dy2, mode="lines+markers", name="edge_order=2"))
fig.update_layout(title="Comparison of Boundary Edge Orders", xaxis_title="x", yaxis_title="dy", height=400)
fig.show()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 . Taking its analytic derivative yields:
which is of comparable accuracy to the central difference and recovers it if the points are equally spaced.