[英]How to take derivative in sympy with respect to a vector?
I want to know if it is possible in sympy
to take derivatives of polynomials and expressions using vector notation. 我想知道在
sympy
是否可以使用向量符号来取多项式和表达式的导数。 For example, if I have an expression as a function of two coordinates, x1 and x2, can I just make one call to diff(x)
, where x
is a vector of x1
and x2
, or do I need to make two separate diff
calls to x1
and x2
, and stack them in a matrix? 例如,如果我有一个表达式作为两个坐标x1和x2的函数,我可以只调用
diff(x)
,其中x
是x1
和x2
的向量,还是需要创建两个单独的diff
调用x1
和x2
,并将它们堆叠在矩阵中?
This illustrates what works, versus what I want to work ideally: 这说明了什么有效,而我想理想地工作:
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 :(
Is there a way to take derivatives with respect to vectors in sympy
? 有没有办法对
sympy
向量求导数?
Thank you. 谢谢。
Perhaps you are thinking of the jacobian
: 也许您在考虑
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')]])
And that [x, y]
argument can be Matrix([x, y])
or its transpose, too. 该
[x, y]
参数也可以是Matrix([x, y])
或其转置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.