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. ]
