latex2sympy2
latex2sympy2 is a Python library that parses LaTeX mathematical expressions and converts them into equivalent SymPy forms. It leverages ANTLR for parsing and supports a wide range of features including arithmetic, various alphabets, common mathematical functions, calculus operations (limits, derivatives, integrals), linear algebra (matrices, determinants, transposes), and other functions like binomials. The current version is 1.9.1, released in April 2023, and it maintains an active release cadence.
Warnings
- gotcha latex2sympy2 performs irreversible calculations when processing certain linear algebra operations such as determinants, transposed matrices, and elementary transformations. The converted SymPy output may not perfectly retain the original structure for these specific LaTeX inputs.
- gotcha The differential operator 'd' in LaTeX expressions for derivatives might require specific formatting, e.g., `\mathrm{d}` instead of `d`, to be correctly interpreted by the parser. While `d` often works, `\mathrm{d}` can prevent ambiguity and ensure correct parsing in all contexts.
Install
-
pip install latex2sympy2
Imports
- latex2sympy
from latex2sympy2 import latex2sympy
- latex2latex
from latex2sympy2 import latex2latex
Quickstart
from latex2sympy2 import latex2sympy, latex2latex
# Convert a LaTeX expression to SymPy
tex_expression = r"\frac{d}{dx}(x^{2}+x)"
sympy_expression = latex2sympy(tex_expression)
print(f"LaTeX: {tex_expression}\nSymPy: {sympy_expression}")
# Convert a LaTeX expression, calculate it, and convert back to LaTeX
calculated_latex = latex2latex(tex_expression)
print(f"Calculated LaTeX: {calculated_latex}")
# Example with a simple algebraic expression
tex_algebra = r"x + y = 1"
sympy_algebra = latex2sympy(tex_algebra)
print(f"LaTeX: {tex_algebra}\nSymPy: {sympy_algebra}")