Latex output from sympy does not correctly display in Google Colaboratory Jupyter notebooks

安稳与你 提交于 2019-12-01 00:48:36

问题


I am using Google's Colaboratory platform to run python in a Jupyter notebook. In standard Jupyter notebooks, the output of sympy functions is correctly typeset Latex, but the Colaboratory notebook just outputs the Latex, as in the following code snippet:

import numpy as np
import sympy as sp
sp.init_printing(use_unicode=True)
x=sp.symbols('x')
a=sp.Integral(sp.sin(x)*sp.exp(x),x);a

results in Latex output like this:

$$\int e^{x} \sin{\left (x \right )}\, dx$$

The answer cited in these questions, Rendering LaTeX in output cells in Colaboratory and LaTeX equations do not render in google Colaboratory when using IPython.display.Latex doesn't fix the problem. While it provides a method to display Latex expressions in the output of a code cell, it doesn't fix the output from the built-in sympy functions.

Any suggestions on how to get sympy output to properly render? Or is this a problem with the Colaboratory notebook?


回答1:


I have just made this code snippet to make sympy works like a charm in colab.research.googlr.com !!!

def custom_latex_printer(exp,**options):
    from google.colab.output._publish import javascript
    url = "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.3/latest.js?config=default"
    javascript(url=url)
    return sympy.printing.latex(exp,**options)
init_printing(use_latex="mathjax",latex_printer=custom_latex_printer)

Put it after you imported sympy This one basically tell sympy to embed mathjax library using colab api before they actually output any syntax.




回答2:


You need to include MathJax library before display. Set it up in a cell like this first.

from google.colab.output._publish import javascript
url = "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.3/latest.js?config=default"

Later, you include javascript(url=url) before displaying:

x=sp.symbols('x')
a=sp.Integral(sp.sin(x)*sp.exp(x),x)
javascript(url=url)
a

Then, it will display correctly.



来源:https://stackoverflow.com/questions/52010001/latex-output-from-sympy-does-not-correctly-display-in-google-colaboratory-jupyte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!