用NumPy计算梯度 [英] Calculating gradient with NumPy

查看:454
本文介绍了用NumPy计算梯度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的不明白numpy.gradient函数的作用以及如何将其用于计算多变量函数梯度.

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

我需要计算它的3维梯度(换句话说,我想计算所有变量(q,chi,delta)的偏导数).

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

如何使用NumPy计算该梯度?

How can I calculate this gradient using NumPy?

推荐答案

问题是,numpy无法直接为您提供派生,而您有两种选择:

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

使用NUMPY

本质上,您要做的是在三维中定义一个网格并评估该网格上的功能.然后,将此函数值表馈入numpy.gradient以获得具有每个维(变量)的数值导数的数组.

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).

来自此处的示例

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)

没有NUMPY

您还可以使用集中差异商自己计算导数.

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

从本质上讲,这是numpy.gradient 在做什么用于预定义网格的每个点.

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

这篇关于用NumPy计算梯度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆