如何在 sympy 中对向量求导?

sim*_*ple 5 python symbolic-math sympy python-2.7

我想知道是否可以sympy使用向量表示法求多项式和表达式的导数。例如,如果我有一个表达式作为两个坐标 x1 和 x2 的函数,我可以只调用一次diff(x),其中是和x的向量,还是需要对和进行两次单独的调用,并将它们堆叠在一个矩阵?x1x2diffx1x2

这说明了什么是有效的,以及什么是我想要的理想工作:

import sympy
from sympy.matrices import Matrix

# I understand that this is possible: 
x1 = sympy.symbol.symbols('x1')  
x2 = sympy.symbol.symbols('x2')

expr_1 = x1**2+x2
poly_1 = sympy.poly(expr_1, x1, x2)

print Matrix([[poly_1.diff(x1)],[poly_1.diff(x2)]])

# but is something like this also possible?
x1 = sympy.symbol.symbols('x1')  
x2 = sympy.symbol.symbols('x2')
x_vec = Matrix([[x1],[x2]])

expr_1 = x1**2+x2
poly_1 = sympy.poly(expr_1, x1, x2)

# taking derivative with respect to a vector
poly_1.diff(x_vec)

# should ideally return same as first example: 
'''
Matrix([
[Poly(2*x1, x1, x2, domain='ZZ')],
[   Poly(1, x1, x2, domain='ZZ')]])
'''
# but it fails :(
Run Code Online (Sandbox Code Playgroud)

有没有办法对 中的向量求导数sympy

谢谢。

smi*_*chr 4

也许您正在考虑jacobian

>>> Matrix([Poly(x**2+y,x,y)]).jacobian([x, y])
Matrix([[Poly(2*x, x, y, domain='ZZ'), Poly(1, x, y, domain='ZZ')]])
Run Code Online (Sandbox Code Playgroud)

这个[x, y]论证也可以是Matrix([x, y])或其转置。