SymPy 打印


SymPy 中有多种打印机可用。以下为部分名单:

  • str
  • srepr
  • ASCII 漂亮的打印机
  • Unicode 漂亮的打印机
  • LaTeX
  • MathML
  • Dot

SymPy 对象也可以作为输出发送到各种语言的代码,例如 C、Fortran、Javascript、Theano 和 Python。

SymPy 使用 Unicode 字符以漂亮的打印形式呈现输出。如果你使用 Python 控制台执行 SymPy 会话,则通过调用 init_session() 函数来激活最漂亮的打印环境。

>>> from sympy import init_session 
>>> init_session()

SymPy 1.5.1(Python 3.7.4-64 位)的 IPython 控制台(地面类型:python)。

执行了这些命令:

>>> from __future__ import division
>>> from sympy import *
>>> x, y, z, t = symbols('x y z t')
>>> k, m, n = symbols('k m n', integer=True)
>>> f, g, h = symbols('f g h', cls=Function)
>>> init_printing()

文档可以在 https://docs.sympy.org/1.5.1/。

>>> Integral(sqrt(1/x),x)

$\int \sqrt\frac{1}{x} dx$

如果没有安装 LATEX,但安装了 Matplotlib,它将使用 Matplotlib 渲染引擎。如果未安装 Matplotlib,它将使用 Unicode 漂亮打印机。然而,Jupyter notebook 使用 MathJax 来渲染 LATEX。

在不支持 Unicode 的终端中,使用 ASCII 漂亮的打印机。

ASCII Pretty Printer

要使用 ASCII 打印机,请使用 pprint() 函数,并将 use_unicode 属性设置为 False

>>> pprint(Integral(sqrt(1/x),x),use_unicode=False)
Unicode Pretty Printer

Unicode 漂亮打印机也可以从 pprint() 和 pretty() 访问。如果终端支持 Unicode,则会自动使用它。如果 pprint() 无法检测到终端支持 unicode,可以通过 use_unicode=True 强制它使用 Unicode。

要获得表达式的 LATEX 形式,请使用 latex() 函数。

>>> print(latex(Integral(sqrt(1/x),x)))

\int \sqrt{\frac{1}{x}}\, dx

你也可以使用 mathml 打印机。为此,导入 print_mathml 函数。字符串版本由 mathml() 函数获得。

>>> from sympy.printing.mathml import print_mathml 
>>> print_mathml(Integral(sqrt(1/x),x))

<申请>

x

<申请>

<申请>

<电源/>

x

-1

>>>mathml(Integral(sqrt(1/x),x))

'xx-1 '