可在Python模块Sympy中以矩阵形式使用的微分运算符 [英] Differential Operator usable in Matrix form, in Python module Sympy

查看:135
本文介绍了可在Python模块Sympy中以矩阵形式使用的微分运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们需要两个差分运算符[B][C]的矩阵,例如:

We need two matrices of differential operators [B] and [C] such as:

B = sympy.Matrix([[ D(x), D(y) ],
                  [ D(y), D(x) ]])

C = sympy.Matrix([[ D(x), D(y) ]])

ans = B * sympy.Matrix([[x*y**2],
                        [x**2*y]])
print ans
[x**2 + y**2]
[      4*x*y]

ans2 = ans * C
print ans2
[2*x, 2*y]
[4*y, 4*x]

这也可以用于计算矢量场的卷曲度,例如:

This could also be applied to calculate the curl of a vector field like:

culr  = sympy.Matrix([[ D(x), D(y), D(z) ]])
field = sympy.Matrix([[ x**2*y, x*y*z, -x**2*y**2 ]])

要使用Sympy解决此问题,必须创建以下Python类:

To solve this using Sympy the following Python class had to be created:

import sympy

class D( sympy.Derivative ):
    def __init__( self, var ):
        super( D, self ).__init__()
        self.var = var

    def __mul__(self, other):
        return sympy.diff( other, self.var )

仅此类可解决差分运算符的矩阵在左侧相乘的情况.这里diff仅在已知要区分的函数时执行.

This class alone solves when the matrix of differential operators is multiplying on the left. Here diff is executed only when the function to be differentiated is known.

要解决变数运算符矩阵在右侧相乘的问题,必须以下列方式更改核心类Expr中的__mul__方法:

To workaround when the matrix of differential operators is multiplying on the right, the __mul__ method in the core class Expr had to be changed in the following way:

class Expr(Basic, EvalfMixin):
    # ...
    def __mul__(self, other):
        import sympy
        if other.__class__.__name__ == 'D':
            return sympy.diff( self, other.var )
        else:
            return Mul(self, other)
    #...

它工作得很好,但是Sympy中应该有一个更好的本机解决方案来处理此问题. 有人知道这可能是什么吗?

It works pretty well, but there should be a better native solution in Sympy to handle this. Does anybody know what it might be?

推荐答案

此解决方案适用于其他答案和

This solution applies the tips from the other answers and from here. The D operator can be defined as follows:

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