Calculating Derivatives with np.gradient
A powerful tool for numerical analysis in Python
What is np.gradient?
Definition:
np.gradient is a NumPy function that calculates the
gradient (numerical derivative) of an N-dimensional array. It uses the central difference method
for interior points and one-sided differences for boundary points.
Basic Usage: 1D Array
For a simple list of numbers, np.gradient computes the rate of change between
elements.
import numpy as np
# Create a linear array [0, 2, 4, 6, 8]
y = np.array([0, 2, 4, 6, 8])
# Calculate gradient
dydx = np.gradient(y)
print(dydx)
# Output: [2. 2. 2. 2. 2.]
Why 2? Since the array increases by 2 at each step, the derivative (slope) is
constant at 2.
How It Works (The Math)
NumPy uses the central difference formula for interior points:
f'(x) ≈ (f(x+h) - f(x-h)) / 2h
Where h is the spacing between points (default is 1).
Advanced: Defining Point Spacing
If your data points aren't spaced by 1 unit, you must specify the spacing dx.
x = np.array([0, 2, 4, 6, 8])
y = x**2 # y = [0, 4, 16, 36, 64]
# Specify that x-points are 2 units apart
gradient = np.gradient(y, 2)
# Expected derivative of x^2 is 2x
# At x=4, 2x = 8. Let's check:
# Output surrounding elements approx matches 2x2D Arrays (Image Processing)
For images or 2D fields, np.gradient returns two arrays: the gradient in the
y-direction (rows) and the x-direction (columns).
image = np.random.random((100, 100))
# Get gradients for both axes
grad_y, grad_x = np.gradient(image)