我正在使用Google的Colaboratory平台在Jupyter笔记本中运行python。在标准Jupyter笔记本中,sympy函数的输出正确地排版了Latex,但是Colaboratory笔记本仅输出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输出以正确呈现的任何建议?还是合作笔记本有问题吗?
答案 0 :(得分:6)
我刚刚制作了此代码段,以使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库。
答案 1 :(得分:2)
在显示之前,您需要包括MathJax库。首先将其设置在像这样的单元格中。
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)
x=sp.symbols('x')
a=sp.Integral(sp.sin(x)*sp.exp(x),x)
javascript(url=url)
a
然后,它将正确显示。
答案 2 :(得分:1)
使用colab的mathjax并将配置文件设置为TeX-MML-AM_HTMLorMML对我有用。下面是代码:
class Product{
public Product(){}
@CommandHandler
public Product(CreateProductCommand command){
apply(new CreateProductEvent(command.id));
}
@CommandHandler
public Product(UpdateProductCommand command){
load(command.id)
...
apply(new UpdateProductEvent(command.id));
}
}