pythonsympy

Can we get "-x^{2}+1" instead of "1-x^{2}" with sympy.latex(-x**2+1)?


I need -x^{2}+1 rather than 1-x^{2} with sympy.latex(-x**2+1).

from sympy import symbols, latex
x = symbols('x')
print(-x**2+1)
print(latex(-x**2+1))

Output:

1 - x**2
1 - x^{2}

Is it possible to change the default format?


Solution

  • As suggested in comments, you can use the order argument to change the result ordering!

    https://docs.sympy.org/latest/modules/printing.html#sympy.printing.latex.latex

    order: string, optional
    Any of the supported monomial orderings (currently 'lex', 'grlex', or 'grevlex'), 'old', and 'none'. This parameter does nothing for .Mul objects. Setting order to 'old' uses the compatibility ordering for ~.Add defined in Printer. For very large expressions, set the order keyword to 'none' if speed is a concern.

    >>> print(latex(-x**2+1))
    1 - x^{2}
    >>> print(latex(-x**2+1, order="lex"))
    - x^{2} + 1
    

    Casually, it could be worth a PR to set this ordering for None when the expression is literally quite short (by count of atoms?), but I'm not sufficiently familiar with real-world cases of it