【问题标题】:Colab not rendering mathjax sympy outputColab 不渲染 mathjax sympy 输出
【发布时间】:2019-05-27 05:57:53
【问题描述】:

Google Colab 不会渲染由 sympy 生成的 Python 单元的 Mathjax 输出。我没有得到图形输出,而是得到会生成输出的降价命令。

比如下面的代码:

import numpy as np
import sympy as sp
x1 = np.array([1,1,1,1]).reshape(-1,1)
x2 = np.array([2,3,4,5]).reshape(-1,1)
x3 = np.array([3,4,5,6]).reshape(-1,1)
A = np.concatenate([x1,x2,x3],axis=1)
A = sp.Matrix(A)
x = sp.Matrix([1,1,1])
sp.init_printing(use_latex='mathjax')
A,x

给我输出字符串:

$\displaystyle \left( \left[\begin{matrix}1 & 2 & 3\1 & 3 & 4\1 & 4 & 5\1 & 5 & 6\end{matrix}\right], \ \left[\begin{matrix}1\1\1\end{matrix}\right]\right)$

而不是渲染图像本身。

【问题讨论】:

    标签: python latex sympy google-colaboratory mathjax


    【解决方案1】:

    这对我有用(来自较早的帖子 https://*.com/a/49584891/2417833 - 不适用于 colab 的 mathjax):

    import numpy as np
    import sympy as sp
    from google.colab.output._publish import javascript
    javascript(url="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.3/latest.js?config=default")
    x1 = np.array([1,1,1,1]).reshape(-1,1)
    x2 = np.array([2,3,4,5]).reshape(-1,1)
    x3 = np.array([3,4,5,6]).reshape(-1,1)
    A = np.concatenate([x1,x2,x3],axis=1)
    A = sp.Matrix(A)
    x = sp.Matrix([1,1,1])
    sp.init_printing(use_latex='mathjax')
    A,x
    

    【讨论】:

    • 我从另一篇文章中得到了答案(链接丢失,抱歉),但我对其进行了详细阐述,以便可以将其放在笔记本中并在 Windows 和 Colab 中运行。
    • 代码是这个``` {python} import sys import sympy as sp if sys.platform == 'linux': def custom_latex_printer(exp,**options): from google.colab.output。 _publish import javascript url = "cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.3/…" javascript(url=url) return sp.printing.latex(exp,**options) sp.init_printing(use_latex="mathjax",latex_printer=custom_latex_printer) else: sp.init_printing(use_latex ="mathjax") ```