NumPy provides the numpy.gradient function to compute the numerical gradient of an array. This function calculates the gradient of an N-dimensional array and returns a list of N arrays, where each array represents the gradient along a corresponding dimension.
In the context of numerical arrays, the gradient represents the rate of change of the array’s values. For a discrete array, the gradient is numerically approximated using finite differences. Essentially, numpy.gradient estimates how much and in what direction the values in the array are changing from one element to the next.
Here is an example of how you can use numpy.gradient to calculate the gradient of a 1-dimensional array:
import numpy as np # Define a 1-dimensional array x = np.array([1, 2, 4, 7, 11]) # Calculate the gradient of the array gradient = np.gradient(x) print(gradient) # Output: [ 1. 2. 3. 4. 5.]
In this example, the variable gradient stores a one-dimensional array representing the numerical gradient of the input array x.
For a 1D array, the gradient calculation is relatively straightforward. For each element (except the boundaries), numpy.gradient calculates the difference between the value at that point and the values of its neighbors to estimate the rate of change. At the boundaries, it uses either a forward or backward difference.
The numpy.gradient function can also be employed to calculate the gradient of a two-dimensional array along each of its dimensions:
import numpy as np # Define a 2-dimensional array x = np.array([[1, 2, 4], [7, 11, 16]]) # Calculate the gradient of the array along each dimension dx, dy = np.gradient(x) print("Gradient along first dimension:") print(dx) # Output: # [[ 3. 3. 3.] # [ 4. 4. 4.]] print("Gradient along second dimension:") print(dy) # Output: # [[ 2. 2.] # [ 5. 5.]]
In this two-dimensional example, dx represents the gradient of the input array x along the first axis (rows), and dy represents the gradient along the second axis (columns).