加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – Sympy:修改衍生物的LaTeX输出

发布时间:2020-12-16 22:38:56 所属栏目:Python 来源:网络整理
导读:在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} 有没有办法强迫

在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}

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

最佳答案
您可以继承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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读