Calculating gradient with NumPy

Python numpy.gradient() Method: In this tutorial, we will learn about the numpy.gradient(), how to calculate gradient with NumPy? By Pranit Sharma Last updated : May 05, 2023

Python numpy.gradient() Method

The numpy.gradient() is used to return the gradient of an N-dimensional array. The gradient is computed using second-order accurate central differences in the interior points and either first or second-order accurate one-sides (forward or backward) differences at the boundaries.

In NumPy, we need to define a grid in three dimensions and evaluate the function of this grid. Afterward, we will feed this table of function values to numpy.gradient() to get an array with the numerical derivative for every dimension (variable).

Syntax:

numpy.gradient(f, *varargs, axis=None, edge_order=1)

How to calculate gradient with NumPy?

To calculate the gradient with NumPy, you can use numpy.gradient() method by passing the specified parameters such as f (array_like), varargs (list of scalar or array, optional), edge_order ({1, 2}, optional), axis (None or int or tuple of ints, optional), and get the gradient of an N-dimensional array based on the given parameters.

Let us understand with the help of an example,

Python program for calculating gradient with NumPy

# Import numpy
import numpy as np

# Creating a grid
x,y,z = np.mgrid[-2:1:2, -2:1:2, -2:1:2]

# Display 3 dimensions
print("x:\n",x,"\n")
print("y:\n",y,"\n")
print("z:\n",z,"\n")

# Defining an expresion
ex = 2*x**2 + 3*y**2 - 4*z

# Calculating gradient
x_r = np.gradient(ex)
y_r = np.gradient(ex)
z_r = np.gradient(ex)

# Display result
print("x:\n",x_r,"\n")
print("y:\n",y_r,"\n")
print("z:\n",z_r,"\n")

Output

x:
 [[[-2 -2]
  [-2 -2]]

 [[ 0  0]
  [ 0  0]]] 

y:
 [[[-2 -2]
  [ 0  0]]

 [[-2 -2]
  [ 0  0]]] 

z:
 [[[-2  0]
  [-2  0]]

 [[-2  0]
  [-2  0]]] 

x:
 [array([[[-8., -8.],
        [-8., -8.]],

       [[-8., -8.],
        [-8., -8.]]]), array([[[-12., -12.],
        [-12., -12.]],

       [[-12., -12.],
        [-12., -12.]]]), array([[[-8., -8.],
        [-8., -8.]],

       [[-8., -8.],
        [-8., -8.]]])] 

y:
 [array([[[-8., -8.],
        [-8., -8.]],

       [[-8., -8.],
        [-8., -8.]]]), array([[[-12., -12.],
        [-12., -12.]],

       [[-12., -12.],
        [-12., -12.]]]), array([[[-8., -8.],
        [-8., -8.]],

       [[-8., -8.],
        [-8., -8.]]])] 

z:
 [array([[[-8., -8.],
        [-8., -8.]],

       [[-8., -8.],
        [-8., -8.]]]), array([[[-12., -12.],
        [-12., -12.]],

       [[-12., -12.],
        [-12., -12.]]]), array([[[-8., -8.],
        [-8., -8.]],

       [[-8., -8.],
        [-8., -8.]]])]

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.