Latex equations using SymPy
SymPy is a symbolic mathematics package in Python. Even if you are not interested in performing symbolic mathematical calculations, you should probably install it for one very useful function: sympy.latex().
sympy.latex() converts mathematical expressions into Latex equations.
SymPy can create images of equations, but the images in the following examples are dynamically generated using the online latex equation editor at Code Cogs.
>>> x = Symbol("x")
>>> a = 1/( (x+2)*(x+1) )
>>> latex(a)
\frac{1}{\left(x + 1\right) \left(x + 2\right)}
>>> latex(Integral(x**2+sin(x)*exp(x**2),x))
\int x^{2} + e^{x^{2}} \operatorname{sin}\left(x\right)\,dx
>>> latex(Eq(Integral(x,x), x**2/2))
\int x\,dx = \frac{1}{2} x^{2}
>>> a = Integral(x, (x, 1, 2))
>>> s = Eq(a, a.doit())
>>> latex(s)
\int_{1}^{2} x\,dx = \frac{3}{2}
I think this is easier than using visual equation editors since we can simply type the equation as a Python expression, and have it converted into Latex with just one function call.
Installing SymPy is also very easy:
$ pip install sympy
In addition to generating latex equations, SymPy can also pretty print the equation on to the terminal, and can generate “png” and “dvi” images of the equations. The SymPy tutorial and manual give several examples of these.
If you want a fully featured mathematical package that is free and open source, then get Sage. Sage is a symbolic mathematics application that uses Python as its underlying language. It uses SymPy, and has many more formatting and plotting functions.

Hi,
Thnx for the post. Really helped me setup sympy and get the latex equation. I had to make a few updates though in the syntax (not sure if it was because of a version change). For your first example, I had to use,
import sympy
x = sympy.symbols(“x”)
a = 1/( (x+2)*(x+1) )
print sympy.latex(a)
But then, could you tell me where the “Integral” function comes from in python? Guess I dont have the right libraries. Is it from scipy? I see only scipy.integrate.
Thanks in advance for ur reply..
-amrudesh
Hello,
Integral is from sympy itself. Look at examples at http://docs.sympy.org/0.7.2/tutorial.html .
Hi Prashanth,
Thnx . I checked . It seems to have not changed to “integrate” . Now, it works.. :)