我正在使用 Google 的 Colaboratory 平台在 Jupyter 笔记本中运行 python。在标准 Jupyter notebook 中,sympy 函数的输出正确排版 Latex,但 Colaboratory notebook 仅输出 Latex,如下面的代码片段所示:
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
导致 Latex 输出如下:
$$\int e^{x} \sin{\left (x \right )}\, dx$$
这些问题中引用的答案,Rendering LaTeX in output cells in Colaboratory和 LaTeX equations do not render in google Colaboratory when using IPython.display.Latex不能解决问题。虽然它提供了一种在代码单元格的输出中显示 Latex 表达式的方法,但它并没有修复内置 sympy 函数的输出。
关于如何让 sympy 输出正确渲染的任何建议?或者这是 Colaboratory 笔记本的问题?
最佳答案
我刚刚制作了这个代码片段,让 sympy 像 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)
把它放在你导入 sympy 之后
这个基本上告诉 sympy 在他们实际输出任何语法之前使用 colab api 嵌入 mathjax 库。
关于来自 sympy 的 Latex 输出无法在 Google Colaboratory Jupyter 笔记本中正确显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52010001/