Enforce custom ordering on Sympy print

前端 未结 1 720
忘了有多久
忘了有多久 2021-02-08 12:47

SymPy does a wonderful work keeping track of all the operations I do to my symbolic expressions. But a the moment of printing the result for latex output I would li

1条回答
  •  北恋
    北恋 (楼主)
    2021-02-08 13:16

    If you can put the terms in the order you want then setting the order flag for the Latex printer to 'none' will print them in that order.

    >>> import sympy as sp
    >>> sp.init_printing()
    >>> U,tp, z, d = sp.symbols('U t_\perp z d')
    >>> eq=z+tp**2+U+U/(z-3*tp)+d
    

    Here we put them in order (knowing the power of tp is 2) and rebuild as an Add with evaluate=False to keep the order unchanged

    >>> p = Add(*[eq.coeff(i)*i for i in (z, U, tp**2, d)],evaluate=False)
    

    And now we print that expression with a printer instance with order='none':

    >>> from sympy.printing.latex import LatexPrinter
    >>> s=LatexPrinter(dict(order='none'))
    >>> s._print_Add(p)
    z + U \left(1 + \frac{1}{z - 3 t_\perp}\right) + t_\perp^{2} + d
    

    0 讨论(0)
提交回复
热议问题