Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 459
user2243748 Avatar asked Apr 04 '13 08:04

user2243748


2 Answers

Take a look at this Latex -> Sympy converter, it works great for a big subset of Latex:

https://github.com/augustt198/latex2sympy

like image 182
nicodjimenez Avatar answered Oct 14 '22 05:10

nicodjimenez


I would look at tools that convert latex to mathml, such as (via google search): http://www.mathtowebonline.com/

Then you can process the XML that comes out of this. However, you should be careful interpreting the result as a mathematical expression. Such tools may guarantee the textual representation is equal, but the bracketing (grouping) of operands with their operators may not be what you expect. In general you will see less nesting. Operators that are just next to each other that we interpret by convention as being nested will simply be converted to sibling elements in the XML format. If you try to interpret this as formulas there is still some work left to be done (recovering the nested structure in the right way).

like image 42
Jurgen Vinju Avatar answered Oct 14 '22 04:10

Jurgen Vinju