如何通过sympy在ipython笔记本上打印漂亮?

问题描述 投票:37回答:3

我试过pprintprint,前者只打印Unicode版本,而后者不做漂亮的打印。

from sympy import symbols, Function
import sympy.functions as sym
from sympy import init_printing
init_printing(use_latex=True)
from sympy import pprint
from sympy import Symbol

x = Symbol('x')

# If a cell contains only the following, it will render perfectly.
(pi + x)**2

# However I would like to control what to print in a function, 
# so that multiple expressions can be printed from a single notebook cell.
pprint((pi + x)**2)
python jupyter-notebook jupyter sympy pretty-print
3个回答
56
投票

你需要使用显示器:

from IPython.display import display

display(yourobject)

它会选择合适的表示形式(text / LaTex / png ...),默认导入最近版本的IPython(6.0+)显示,我们仍然建议显式导入它。


26
投票

问题出在你的init_printing语句中。在笔记本中,你不想运行latex,而应该使用mathjax,所以请尝试使用:

init_printing(use_latex='mathjax')

当我使用它时,我到处都能得到正常的漂亮打印,即使我有一个表情符号作为单元格的最后一行。


1
投票

这有效,

from IPython.display import display, Latex
from sympy import *

x = symbols('x')
display(x)

int_x = Integral(cos(x)*exp(x), x)
result = "$${} = {}$$".format(latex(int_x), latex(int_x.doit()))
display(Latex(result))

derv_x = Derivative(cos(x)*exp(x), x)
result = "$${} = {}$$".format(latex(derv_x), latex(derv_x.doit()))
display(Latex(result))

亲自尝试一下。

© www.soinside.com 2019 - 2024. All rights reserved.