How to use gradient in Numpy

In NumPy, the gradient of an array can be computed using the numpy.gradient function. This function calculates the gradient of an N-dimensional array, and returns a list of N arrays, each of which gives the gradient along a particular dimension.

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, gradient is a 1-dimensional array that gives the gradient of the input array x.

See also  How to Get the Length of a NumPy Array

You can also calculate the gradient of a 2-dimensional array along each dimension using the numpy.gradient function:

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 example, dx gives the gradient of the input array x along the first dimension, and dy gives the gradient along the second dimension.

See also  How to convert array from float to int in Numpy?