首页 文章

Sympy:修改衍生物的LaTeX输出

提问于
浏览
5

在Sympy中,是否可以修改使用latex()输出函数派生的方式?默认是非常麻烦的 . 这个:

f = Function("f")(x,t)
print latex(f.diff(x,x))

将输出

\frac{\partial^{2}}{\partial x^{2}}  f{\left (x,t \right )}

这很冗长 . 如果我更喜欢像

f_{xx}

有没有办法强迫这种行为?

1 回答

  • 3

    您可以继承 LatexPrinter 并定义自己的 _print_Derivative . Here是当前的实现 .

    也许是这样的

    from sympy import Symbol
    from sympy.printing.latex import LatexPrinter
    from sympy.core.function import UndefinedFunction
    
    class MyLatexPrinter(LatexPrinter):
        def _print_Derivative(self, expr):
            # Only print the shortened way for functions of symbols
            function, *vars = expr.args
            if not isinstance(type(function), UndefinedFunction) or not all(isinstance(i, Symbol) for i in vars):
                return super()._print_Derivative(expr)
            return r'%s_{%s}' % (self._print(Symbol(function.func.__name__)), ' '.join([self._print(i) for i in vars]))
    

    哪个像

    >>> MyLatexPrinter().doprint(f(x, y).diff(x, y))
    'f_{x y}'
    >>> MyLatexPrinter().doprint(Derivative(x, x))
    '\\frac{d}{d x} x'
    

    要在Jupyter笔记本中使用它,请使用

    init_printing(latex_printer=MyLatexPrinter().doprint)
    

相关问题