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()

IPython 控制檯,適用於 SymPy 1.5.1(Python 3.7.4-64 位)(基本型別: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))

<apply>

<int/>

<bvar>

<ci>x</ci>

</bvar>

<apply>

<root/>

<apply>

<power/>

<ci>x</ci>

<cn>-1</cn>

</apply>

</apply>

</apply>

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

'<apply><int/><bvar><ci>x</ci></bvar><apply><root/><apply><power/><ci>x</ci><cn>-1</cn></apply></apply></apply>'

廣告

© . All rights reserved.