1

Hi and thanks in advance for your help. I'm trying to get nice math formatting mixed with sympy expressions. I'm using jupyter-notebook.

I can get latex and nice sympy printing on separate lines, but can't seem to figure out a way to combine them into one line. The code below prints three lines; the third line should be the combination of the first two. Hopefully there is an elegant solution that I haven't figured out (bit of a Python noob).

import sympy as sym
from IPython.display import display, Math
sym.init_printing()

x = sym.symbols('x')

expr = sym.sqrt(3) * x**3
display(Math('\\frac{1}{2} ') )
display(expr)
display(Math('\\frac{1}{2} %s' %expr) )

1 Answers1

3

When you use string formatting, the str method implemented by sympy is used to convert the expression into a string. However, the output of str is not intended for LaTeX output, see the documentation of str:

To get a string form of an expression, use str(expr). This is also the form that is produced by print(expr). String forms are designed to be easy to read, but in a form that is correct Python syntax so that it can be copied and pasted. The str() form of an expression will usually look exactly the same as the expression as you would enter it.

So the output is intended to be valid python code:

>> str(expr)
'sqrt(3)*x**3'

To get the expression in LaTeX format, sympy provivdes the latex function. It can be invoked as follows:

>> sym.latex(expr)
'\\sqrt{3} x^{3}'

So, simply change your last line to

display(Math('\\frac{1}{2} %s' %sym.latex(expr)))

and it should look as intended.

jdamp
  • 1,379
  • 1
  • 15
  • 22