Display command output as math : IPython.display.Math?

Hi there,

my first topic.

I am using notebooks for teaching maths and python to under graduate students. Here is an example of the python code I use to have a math output

Given some symbolic computation

import sympy as sym
x = sym.symbols('x')
I = sym.integrate(1/(1+x**2), (x, 0, 1))

This is the display related part

sym.init_printing(use_latex='mathjax', use_unicode=True)
import IPython.display.Math
IPython.display.Math(rf'\int_{{t=0}}^1 \frac{{1}}{{1+t^2}}\,\text{{d}}t = {sympy.latex(I)}')

The output is
Capture d’écran 2020-01-23 à 11.25.41

As JupyterLab does not know about iPython object, how can I convert this last code to JupyterLab ?

Thanks

Building on my example from here that works in JupyterLab, I converted your code. Works in current JupyterLab:

from IPython.display import Markdown, display
def printmd(string):
    display(Markdown(string))
import sympy as sym
x = sym.symbols('x')
I = sym.integrate(1/(1+x**2), (x, 0, 1))
equation = r'$$\int_{{t=0}}^1 \frac{{1}}{{1+t^2}}\,\text{d}t$$'
printmd('**THE EQUATION:**')
printmd(f'{equation}')
printmd('**THE RESULT:**')
printmd(f'$$ = {sym.latex(I)}$$')
printmd('**COMBINED:**')
printmd(r'$$\int_{{t=0}}^1 \frac{{1}}{{1+t^2}}\,\text{d}t' + f' = {sym.latex(I)}$$')
printmd('**OR, COMBINED:**')
printmd(equation[:-2] + f' = {sym.latex(I)}$$') #alternative way to leave off right-side dollar signs

Related notes: Python’s new f-strings are awesome; however, mixing f-strings (and even the str.format() method) with integral notation is a bit of a nightmare because of the braces. And just best avoided, if possible. Luckily, you weren’t substituting in the left side, but I imagine approaches like this will help with that. In current versions of Jupyter, both JupyterLab and the classic interface you can use dollar signs to ‘fence’ LaTeX code in markdown cells and have it rendered in the notebook via MathJax. The trick I show there making a printmd() function just brings the markdown rendering to the code cells as well.

And I’ll add that this works for me in JupyterLab:

from IPython.display import Math
Math(rf'\int_{{t=0}}^1 \frac{{1}}{{1+t^2}}\,\text{{d}}t = ')
2 Likes

That is nice because more in line with original post and doesn’t require cutting off dollar signs like mine to combine:

from IPython.display import Math
Math(rf'\int_{{t=0}}^1 \frac{{1}}{{1+t^2}}\,\text{{d}}t = {sym.latex(I)}')