最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin4浏览0评论

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?

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?

Share Improve this question edited Mar 18 at 18:45 D G asked Mar 18 at 18:39 D GD G 8298 silver badges15 bronze badges 1
  • 1 Isn't that what the order argument is for? – o11c Commented Mar 18 at 20:00
Add a comment  | 

2 Answers 2

Reset to default 3

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

https://docs.sympy./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

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}'
发布评论

评论列表(0)

  1. 暂无评论