【问题标题】:How to take derivative in sympy with respect to a vector?如何对向量求导?
【发布时间】:2023-03-30 13:59:02
【问题描述】:

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

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

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 :(

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

谢谢。

【问题讨论】:

    标签: python python-2.7 sympy symbolic-math


    【解决方案1】:

    也许你在想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')]])
    

    [x, y] 参数也可以是 Matrix([x, y]) 或其转置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-04
      • 1970-01-01
      • 2021-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-02
      相关资源
      最近更新 更多