Search code examples
pythonmathsympymathjaxmathml

When Sympify is executed, the order of expressions is switched (Python's Sympy)


I ran the following program

from sympy import *

str = "Abs(a)*(β-α)**3/6"
print(str)
print(sympify(str))

The execution result was as follows.

Abs(a)*(β-α)**3/6
(-α + β)**3*Abs(a)/6

As a result of executing sympify, the order of the expressions has changed.

I want to match the execution results as follows.

Abs(a)*(β-α)**3/6
Abs(a)*(β-α)**3/6

What should I do?


The reason why I want to do this is that I don't want to make it look weird when converting an expression to mathml format.

str = "Abs(a)*(β-α)**3/6"
print(mathml(sympify(str),printer='presentation'))

When the above program is executed, the following is output.

<mrow><mfrac><mrow><msup><mfenced><mrow><mrow><mo>-</mo><mi>&#945;</mi></mrow><mo>+</mo><mi>&#946;</mi></mrow></mfenced><mn>3</mn></msup><mo>&InvisibleTimes;</mo><mrow><mfenced clos
e="|" open="|"><mi>a</mi></mfenced></mrow></mrow><mn>6</mn></mfrac></mrow>

It looks like the image below.

enter image description here

I want the formula to look like the image below.

enter image description here


Solution

  • If you apply the following diff to SymPy, I think your case will work:

    diff --git a/sympy/printing/str.py b/sympy/printing/str.py
    index ee560ca..cb0db5e 100644
    --- a/sympy/printing/str.py
    +++ b/sympy/printing/str.py
    @@ -51,6 +51,8 @@ def _print_Add(self, expr, order=None):
    
             PREC = precedence(expr)
             l = []
    +        if len(terms) == 2 and str(terms[0])[0] == '-' and str(terms[1])[0] != '-':
    +            terms.reverse()
             for term in terms:
                 t = self._print(term)
                 if t.startswith('-'):
    

    (It prints b - a as the same instead of as -a + b with that change.)