Sympy 简明教程

SymPy - Symbolic Computation

符号计算指的是用于操纵数学表达式和其他数学对象的算法的开发。符号计算将数学与计算机科学结合起来,使用数学符号来求解数学表达式。计算机代数系统(CAS),如 SymPy,使用传统手工方法中使用的相同符号精确求解(非近似)代数表达式。举个例子,我们可以像下面给出的那样,使用 Python 的 math 模块计算一个数的平方根 -

Symbolic computation refers to development of algorithms for manipulating mathematical expressions and other mathematical objects. Symbolic computation integrates mathematics with computer science to solve mathematical expressions using mathematical symbols. A Computer Algebra System (CAS) such as SymPy evaluates algebraic expressions exactly (not approximately) using the same symbols that are used in traditional manual method. For example, we calculate square root of a number using Python’s math module as given below −

>>> import math
>>> print (math.sqrt(25), math.sqrt(7))

上述代码段的输出如下:

The output for the above code snippet is as follows −

5.0 2.6457513110645907

5.0 2.6457513110645907

正如你所见,7 的平方根被近似计算。但在 SymPy 中,非完全平方数的平方根默认情况下都未经评估,如下所示:

As you can see, square root of 7 is calculated approximately. But in SymPy square roots of numbers that are not perfect squares are left unevaluated by default as given below −

>>> import sympy
>>> print (sympy.sqrt(7))

上述代码段的输出如下:

The output for the above code snippet is as follows −

sqrt(7)

sqrt(7)

使用以下代码段,可以用符号方式简化和显示表达式的结果:

It is possible to simplify and show result of expression symbolically with the code snippet below −

>>> import math
>>> print (math.sqrt(12))

上述代码段的输出如下:

The output for the above code snippet is as follows −

3.4641016151377544

3.4641016151377544

您需要使用下面的代码段来使用 sympy 执行相同的操作:

You need to use the below code snippet to execute the same using sympy −

##sympy output
>>> print (sympy.sqrt(12))

其输出如下:

And the output for that is as follows −

2*sqrt(3)

2*sqrt(3)

在 Jupyter Notebook 中运行时,SymPy 代码会利用 MathJax 库以 LaTeX 形式渲染数学符号。这在下面的代码片段中有所体现 -

SymPy code, when run in Jupyter notebook, makes use of MathJax library to render mathematical symbols in LatEx form. It is shown in the below code snippet −

>>> from sympy import *
>>> x=Symbol ('x')
>>> expr = integrate(x**x, x)
>>> expr

在 Python shell 中执行上面的命令后,将生成以下输出 -

On executing the above command in python shell, following output will be generated −

Integral(x**x, x)

它与下式等价

Which is equivalent to

$\int \mathrm{x}^{x}\,\mathrm{d}x$

可以使用传统的符号来表示非完全平方数的平方根,如下所示

The square root of a non-perfect square can be represented by Latex as follows using traditional symbol −

>>> from sympy import *
>>> x=7
>>> sqrt(x)

上述代码段的输出如下:

The output for the above code snippet is as follows −

$\sqrt7$

符号计算系统(如 SymPy)能够以符号形式执行各种计算(如导数、积分和极限,求解方程,使用矩阵)。SymPy 包含不同的模块,这些模块支持绘图、打印(如 LATEX)、物理、统计、组合、数论、几何、逻辑等。

A symbolic computation system such as SymPy does all sorts of computations (such as derivatives, integrals, and limits, solve equations, work with matrices) symbolically. SymPy package has different modules that support plotting, printing (like LATEX), physics, statistics, combinatorics, number theory, geometry, logic, etc.