Mikhail Elizarev Mikhail Elizarev - 3 months ago 25
Python Question

Calculating gradient with NumPy

I really can not understand what numpy.gradient function does and how to use it for computation of multivariable function gradient.

For example, I have such a function:

def func(q, chi, delta):
return q * chi * delta


I need to compute it's 3-dim gradient (in other words, I want to compute partial derivatives with respect to all variables (q, chi, delta)).

How can I calculate this gradient using NumPy?

Answer

The problem is, that numpy can't give you the derivatives directly and you have two options:

With NUMPY

What you essentially have to do, is to define a grid in three dimension and to evaluate the function on this grid. Afterwards you feed this table of function values to numpy.gradient to get an array with the numerical derivative for every dimension (variable).

Example from here:

from numpy import *

x,y,z = mgrid[-100:101:25., -100:101:25., -100:101:25.]

V = 2*x**2 + 3*y**2 - 4*z # just a random function for the potential

Ex,Ey,Ez = gradient(V)

Without NUMPY

You could also calculate the derivative yourself by using the centered difference quotient. centered difference quotient

This is essentially, what numpy.gradient is doing for every point of your predefined grid.