Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

sympy

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?

like image 402
D G Avatar asked Oct 16 '25 16:10

D G


2 Answers

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

like image 115
ti7 Avatar answered Oct 18 '25 06:10

ti7


For one-offs like this I use Symbol fakery to replace the coefficient with a Symbol having a name given by the string of the coefficient:

>>> from sympy import *
>>> fom sympy.abc import x
>>> latex(Symbol('1')-x**2)
'1 - x^{2}'
>>> eq = -1 - x**2
>>> c,e = eq.as_coeff_Add()
>>> latex(Symbol(str(c))+e)
'-1 - x^{2}'
like image 27
smichr Avatar answered Oct 18 '25 05:10

smichr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!