pythonlatexsympy

Convert a LaTex formula to a type that can be used inside SymPy


I want to parse LaTeX formulas and directly use them as SymPy expressions. In other words, what I need is something similar to sympify:

from sympy import sympify
f = sympify('x^2 + sin(y) + 1/2')
print f

but that can take LaTeX expressions (strings) as input, for example:

f = latex_sympify('\frac{x}{1+x}')

Given that sympify is able to convert a string with a regular mathematical expression into a SymPy object, if there is anything that can convert LaTeX into a regular mathematical expression, I guess that would do the trick---but I would prefer to do everything within Python.

Any suggestions will be much appreciated.


Solution

  • latex2sympy is now incorporated into sympy:

    >>> import sympy
    >>> from sympy.parsing.latex import parse_latex
    >>> parse_latex(r'\frac{x}{1+x}')
    x/(x + 1)
    >>> sympy.latex(sympy.diff(_))
    '- \\frac{x}{\\left(x + 1\\right)^{2}} + \\frac{1}{x + 1}'