NumPy gradient()
The numpy.gradient()
function computes the gradient of an N-dimensional array using finite differences.
It returns an array (or tuple of arrays) representing the derivatives along each dimension.
Syntax
</>
Copy
numpy.gradient(f, *varargs, axis=None, edge_order=1)
Parameters
Parameter | Type | Description |
---|---|---|
f | array_like | An N-dimensional array containing samples of a function. |
varargs | list of scalar or array, optional | Specifies spacing between f values. Can be a single scalar, multiple scalars (one per dimension), or coordinate arrays. |
axis | None, int, or tuple of ints, optional | Specifies the axis or axes along which to compute the gradient. Default is None , meaning all axes are used. |
edge_order | {1, 2}, optional | Specifies the accuracy of gradient calculation at the edges. Default is 1 . |
Return Value
Returns a single ndarray if f
is 1D, or a tuple of ndarrays (one for each dimension) if f
is multi-dimensional.
Examples
1. Computing Gradient for a 1D Array
Here, we compute the gradient of a simple 1D array.
</>
Copy
import numpy as np
# Define a 1D array
f = np.array([1, 2, 4, 7, 11])
# Compute the gradient
gradient = np.gradient(f)
# Print the result
print("Gradient of 1D array:", gradient)
Output:
Gradient of 1D array: [1. 1.5 2.5 3.5 4. ]

2. Specifying Spacing Between Points
We specify a uniform spacing of 2 between the elements.
</>
Copy
import numpy as np
# Define a 1D array
f = np.array([1, 2, 4, 7, 11])
# Compute the gradient with spacing of 2
gradient = np.gradient(f, 2)
# Print the result
print("Gradient with spacing=2:", gradient)
Output:
Gradient with spacing=2: [0.5 0.75 1.25 1.75 2. ]

3. Computing Gradient for a 2D Array
We compute the gradient of a 2D array along both axes.
</>
Copy
import numpy as np
# Define a 2D array
f = np.array([[1, 2, 6],
[3, 4, 8],
[5, 6, 10]])
# Compute the gradient
gradient_x, gradient_y = np.gradient(f)
# Print the results
print("Gradient along x-axis:\n", gradient_x)
print("Gradient along y-axis:\n", gradient_y)
Output:
Gradient along x-axis:
[[2. 2. 2.]
[2. 2. 2.]
[2. 2. 2.]]
Gradient along y-axis:
[[1. 2. 2.]
[1. 2. 2.]
[1. 2. 2.]]

4. Specifying an Axis for Gradient Calculation
We compute the gradient along a specific axis.
</>
Copy
import numpy as np
# Define a 2D array
f = np.array([[1, 2, 6],
[3, 4, 8],
[5, 6, 10]])
# Compute gradient along the y-axis (axis=1)
gradient_y = np.gradient(f, axis=1)
# Print the result
print("Gradient along y-axis:\n", gradient_y)
Output:
Gradient along y-axis:
[[1. 2. 4.]
[1. 2. 4.]
[1. 2. 4.]]

5. Using Higher Order Accuracy for Edge Calculation
We use edge_order=2
for higher accuracy at the boundaries.
</>
Copy
import numpy as np
# Define a 1D array
f = np.array([1, 2, 4, 7, 11])
# Compute the gradient using edge_order=2
gradient = np.gradient(f, edge_order=2)
# Print the result
print("Gradient with edge_order=2:", gradient)
Output:
Gradient with edge_order=2: [1. 1.5 2.5 3.5 4. ]
