python - 为 sympy.Derivative 创建自定义打印

标签 python sympy

假设我有一个函数 f(x,y) ,我想要 f 的偏导数写至x显示为 \partial_{x}^{n} f(x,y)所以我创建了以下类

class D(sp.Derivative):
    def _latex(self,printer=None):
        func = printer.doprint(self.args[0])
        b = self.args[1]
        if b[1] == 1 :
            return r"\partial_{%s}%s"%(printer.doprint(b[0]),func)
        else :
            return r"\partial_{%s}^{%s}%s"%(printer.doprint(b[0]),printer.doprint(b[1]),func)

工作正常,但当我使用 doit() 评估导数时,会回到默认行为方法。说我有

x,y = sp.symbols('x,y')
f = sp.Function('f')(x,y)

然后sp.print_latex(D(f,x))给出\partial_{x}f{\left(x,y \right)}这是正确的,但是 sp.print_latex(D(x*f,x).doit())产量x \frac{\partial}{\partial x} f{\left(x,y \right)} + f{\left(x,y \right)} ,这是旧的行为。我该如何解决这个问题?

最佳答案

问题是您没有从父类重写 doit ,它返回普通的 Derivative 对象而不是您的子类。我建议创建一个新的打印机类,而不是创建一个新的Derivative类:

from sympy import *

from sympy.printing.latex import LatexPrinter

class MyLatexPrinter(LatexPrinter):
    def _print_Derivative(self, expr):
        differand, *(wrt_counts) = expr.args
        if len(wrt_counts) > 1 or wrt_counts[0][1] != 1:
            raise NotImplementedError('More code needed...')
        ((wrt, count),) = wrt_counts
        return '\partial_{%s} %s)' % (self._print(wrt), self._print(differand))

x, y = symbols('x, y')
f = Function('f')
expr = (x*f(x, y)).diff(x)

printer = MyLatexPrinter()

print(printer.doprint(expr))

得到x\partial_{x} f{\left(x,y\right)}) + f{\left(x,y\right)}

您可以使用init_printing(latex_printer=printer.doprint)将其设为默认输出。

关于python - 为 sympy.Derivative 创建自定义打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59084096/

相关文章:

python - 张量的加权平均值

python - 多处理 : farming out python functions to a cluster

Python - 递增的数字链不能正常工作

python-3.x - 为什么根据 python -a(b+c) != a(-b-c) ?

python - 替换文件中最后一个字符的简单方法?

python - 在 SymPy 中选择不同的表达式分解

python - 从 sympy/svgmath 生成 SVG 时出错

python - 使用 SymPy 矩阵求根

sympy - sympy 中的一般表达式替换

python - 从多个线程获取结果的更好方法