How to Use NumPy gradient() Function (1D and 2D Array Examples with Finite Differences)

NumPy’s numpy.gradient() computes numerical gradients using central finite differences for 1D arrays or per-axis gradients for multi-dimensional arrays. 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.

See also  Linear Regression with NumPy

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.

See also  How to convert numpy to xyz file?

For 1D arrays, np.gradient(x) returns forward/backward differences at edges and central differences interior, approximating the derivative at each point. 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).

See also  How to resolve MemoryError: Unable to allocate array in Numpy?