Search code examples
pythonlatexsympytex

SymPy automatically processes expressions


I have been using SymPy to convert expressions into latex (to then be rendered by Matplotlib). e.g.

from sympy import latex, sympify
from sympy.abc import x

str = '2*x + 3*x'

TeX = latex(sympify(str))

The problem is that it automatically processes the expression, so 2*x + 3*x automatically becomes 5*x etc; which is not what I want (don't ask!).


Solution

  • Sympy's Add class handles the addition of symbols. You can provide a keyword argument to stop the automatic collection of terms.

    from sympy import Add
    from sympy.abc import x
    
    eq = Add(2*x, 3*x, evaluate=False)
    
    # this will print: 2*x + 3*x
    print eq
    

    This may not be exactly what you want based on your reply to phimuemue's comment.