Sympy 简明教程

SymPy - Quick Guide

SymPy - Introduction

SymPy 是执行符号计算的 Python 库。它是一个 computer algebra system (CAS),可以用作独立应用程序或作为其他应用程序的库。它的实时会话也可在 https://live.sympy.org/ 上获取。因为它是一个纯 Python 库,所以可以用交互模式和编程应用程序使用。SymPy 已成为科学 Python 生态系统中流行的符号库。

SymPy is a Python library for performing symbolic computation. It is a computer algebra system (CAS) that can be used either as a standalone application, as a library to other applications. Its live session is also available at https://live.sympy.org/. Since it is a pure Python library, it can be used as interactive mode and as a programmatic application. SymPy has now become a popular symbolic library for the scientific Python ecosystem.

SymPy 具备广泛的功能,适用于基本符号算术、微积分、代数、离散数学、量子物理学等领域。SymPy 可以以多种格式(包括 LaTeX、MathML 等)设置结果格式。SymPy 按照新 BSD 许可证分发。由 Ondřej ČertíkAaron Meurer 领导的开发人员团队于 2007 年发布了 SymPy 的第一个版本。它的当前版本是 1.5.1。

SymPy has a wide range of features applicable in the field of basic symbolic arithmetic, calculus, algebra, discrete mathematics, quantum physics, etc. SymPy is capable of formatting the results in variety of formats including LaTeX, MathML, etc. SymPy is distributed under New BSD License. A team of developers led by Ondřej Čertík and Aaron Meurer published first version of SymPy in 2007. Its current version is 1.5.1.

SymPy 的一些应用领域有 -

Some of the areas of applications of SymPy are −

  1. Polynomials

  2. Calculus

  3. Discrete maths

  4. Matrices

  5. Geometry

  6. Plotting

  7. Physics

  8. Statistics

  9. Combinatorics

SymPy - Installation

SymPy 有一个重要的先决条件库,名称为 mpmath 。这个 Python 库用于任意精度的实数和复数浮点运算。但是,在按以下方式安装 SymPy 时,Python 的软件包安装程序 PIP 会自动安装它 -

SymPy has one important prerequisite library named mpmath. It is a Python library for real and complex floating-point arithmetic with arbitrary precision. However, Python’s package installer PIP installs it automatically when SymPy is installed as follows −

pip install sympy

其他 Python 分发包(如 Anaconda、Enthought Canopy 等)可能已将 SymPy 内置其中。要验证,可以在 Python 提示符中键入以下内容 -

Other Python distributions such as Anaconda, Enthought Canopy, etc., may have SymPy already bundled in it. To verify, you can type the following in the Python prompt −

>>> import sympy
>>> sympy.__version__

然后你将获得如下 SymPy 当前版本输出 -

And you get the below output as the current version of sympy −

'1.5.1'

'1.5.1'

可在 https://github.com/sympy/sympy 上获取 SymPy 软件包的源代码。

Source code of SymPy package is available at https://github.com/sympy/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.

SymPy - Numbers

SymPy 包中的核心模块包含表示原子数的数字类。该类有两个子类:Float 和 Rational 类。Rational 类由 Integer 类进一步扩展。

The core module in SymPy package contains Number class which represents atomic numbers. This class has two subclasses: Float and Rational class. Rational class is further extended by Integer class.

Float 类表示任意精度的浮点数。

Float class represents a floating point number of arbitrary precision.

>>> from sympy import Float
>>> Float(6.32)

上述代码段的输出如下:

The output for the above code snippet is as follows −

6.32

6.32

SymPy 可以将整数或字符串转换为浮点数。

SymPy can convert an integer or a string to float.

>>> Float(10)

10.0

10.0

Float('1.33E5')# scientific notation

133000.0

133000.0

在转换为浮点数的同时,也可以根据如下内容指定用于精度的数字:

While converting to float, it is also possible to specify number of digits for precision as given below −

>>> Float(1.33333,2)

上述代码段的输出如下:

The output for the above code snippet is as follows −

1.3

1.3

数字 (p/q) 的表示形式通过 Rational 类对象表示,而 q 是非零数字。

A representation of a number (p/q) is represented as object of Rational class with q being a non-zero number.

>>> Rational(3/4)

上述代码段的输出如下:

The output for the above code snippet is as follows −

$\frac{3}{4}$

$\frac{3}{4}$

如果将浮点数传递给 Rational() 构造函数,它将返回其二进制表示的底层值

If a floating point number is passed to Rational() constructor, it returns underlying value of its binary representation

>>> Rational(0.2)

上述代码段的输出如下:

The output for the above code snippet is as follows −

$\frac{3602879701896397}{18014398509481984}$

$\frac{3602879701896397}{18014398509481984}$

为了更简单的表示,指定分母限制。

For simpler representation, specify denominator limitation.

>>> Rational(0.2).limit_denominator(100)

上述代码段的输出如下:

The output for the above code snippet is as follows −

$\frac{1}{5}$

$\frac{1}{5}$

当字符串传给 Rational() 构造函数时,将返回任意精度的有理数。

When a string is passed to Rational() constructor, a rational number of arbitrary precision is returned.

>>> Rational("3.65")

上述代码段的输出如下:

The output for the above code snippet is as follows −

$\frac{73}{20}$

$\frac{73}{20}$

如果传递两个数字参数,也可以获得有理数对象。分子和分母部分作为属性提供。

Rational object can also be obtained if two number arguments are passed. Numerator and denominator parts are available as properties.

>>> a=Rational(3,5)
>>> print (a)
>>> print ("numerator:{}, denominator:{}".format(a.p, a.q))

上述代码段的输出如下:

The output for the above code snippet is as follows −

3/5

3/5

numerator:3, denominator:5

numerator:3, denominator:5

>>> a

上述代码段的输出如下:

The output for the above code snippet is as follows −

$\frac{3}{5}$

$\frac{3}{5}$

SymPy 中的 Integer 类表示任何大小的整数。构造函数可以接受 Float 或 Rational 数,但会舍弃分数部分。

Integer class in SymPy represents an integer number of any size. The constructor can accept a Float or Rational number, but the fractional part is discarded

>>> Integer(10)

上述代码段的输出如下:

The output for the above code snippet is as follows −

10

10

>>> Integer(3.4)

上述代码段的输出如下:

The output for the above code snippet is as follows −

3

3

>>> Integer(2/7)

上述代码段的输出如下:

The output for the above code snippet is as follows −

0

0

SymPy 有一个 RealNumber 类,充当 Float 的别名。SymPy 还将 Zero 和 One 定义为单例类,分别可以通过 S.Zero 和 S.One 访问,如下所示:

SymPy has a RealNumber class that acts as alias for Float. SymPy also defines Zero and One as singleton classes accessible with S.Zero and S.One respectively as shown below −

>>> S.Zero

输出如下 −

The output is as follows −

0

0

>>> S.One

输出如下 −

The output is as follows −

1

1

其他预定义单例数字对象包括 Half、NaN、Infinity 和 ImaginaryUnit。

Other predefined Singleton number objects are Half, NaN, Infinity and ImaginaryUnit

>>> from sympy import S
>>> print (S.Half)

输出如下 −

The output is as follows −

½

½

>>> print (S.NaN)

输出如下 −

The output is as follows −

nan

nan

可以将 Infinity 表示为 oo 符号对象或 S.Infinity

Infinity is available as oo symbol object or S.Infinity

>>> from sympy import oo
>>> oo

上述代码段的输出如下:

The output for the above code snippet is as follows −

$\infty$

$\infty$

>>> S.Infinity

上述代码段的输出如下:

The output for the above code snippet is as follows −

$\infty$

$\infty$

可以将 ImaginaryUnit 数字导入为 I 符号,或者以 S.ImaginaryUnit 为索引符号进行访问,它表示 -1 的平方根

ImaginaryUnit number can be imported as I symbol or accessed as S.ImaginaryUnit and represents square root of -1

>>> from sympy import I
>>> I

执行上述代码片段时,你将获得以下输出 −

When you execute the above code snippet, you get the following output −

i

i

>>> S.ImaginaryUnit

上述片段的输出如下 −

The output of the above snippet is as follows −

i

i

>>> from sympy import sqrt
>>> i=sqrt(-1)
>>> i*i

执行上述代码片段时,你将获得以下输出 −

When you execute the above code snippet, you get the following output −

-1

-1

SymPy - Symbols

Symbol 是 symPy 库中最重要的类。如前所述,符号运算使用符号执行。SymPy 变量是 Symbols 类中的对象。

Symbol is the most important class in symPy library. As mentioned earlier, symbolic computations are done with symbols. SymPy variables are objects of Symbols class.

Symbol() 函数的参数是要分配给变量的符号包含的字符串。

Symbol() function’s argument is a string containing symbol which can be assigned to a variable.

>>> from sympy import Symbol
>>> x=Symbol('x')
>>> y=Symbol('y')
>>> expr=x**2+y**2
>>> expr

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$x^2 + y^2$

$x^2 + y^2$

符号可以包含多个字母。

A symbol may be of more than one alphabets.

>>> s=Symbol('side')
>>> s**3

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$side^3$

$side^3$

SymPy 还有一个 Symbols() 函数,该函数可以同时定义多个符号。字符串包含用逗号或空格分隔的变量名称。

SymPy also has a Symbols() function that can define multiple symbols at once. String contains names of variables separated by comma or space.

>>> from sympy import symbols
>>> x,y,z=symbols("x,y,z")

在 SymPy 的 abc 模块中,所有拉丁字母和希腊字母都被定义为符号。因此,这种方法的便利性在于不需要实例化 Symbol 对象。

In SymPy’s abc module, all Latin and Greek alphabets are defined as symbols. Hence, instead of instantiating Symbol object, this method is convenient.

>>> from sympy.abc import x,y,z

但是,名称 C, O, S, I, N, EQ 是预定义符号。此外,在 abc 模块中没有定义包含多个字母的符号,为此你应该像上面一样使用 Symbol 对象。abc 模块定义了特殊名称,可以检测默认 SymPy 名称空间中的定义。clash1 包含单个字母,clash2 有多个字母冲突符号

However, the names C, O, S, I, N, E and Q are predefined symbols. Also, symbols with more than one alphabets are not defined in abc module, for which you should use Symbol object as above. The abc module defines special names that can detect definitions in default SymPy namespace. clash1 contains single letters and clash2 has multi letter clashing symbols

>>> from sympy.abc import _clash1, _clash2
>>> _clash1

上述片段的输出如下 −

The output of the above snippet is as follows −

{'C': C, 'O': O, 'Q': Q, 'N': N, 'I': I, 'E': E, 'S': S}

{'C': C, 'O': O, 'Q': Q, 'N': N, 'I': I, 'E': E, 'S': S}

>>> _clash2

上述片段的输出如下 −

The output of the above snippet is as follows −

{'beta': beta, 'zeta': zeta, 'gamma': gamma, 'pi': pi}

{'beta': beta, 'zeta': zeta, 'gamma': gamma, 'pi': pi}

索引符号可以使用类似于 range() 函数的语法进行定义。范围由冒号指示。范围类型由冒号右侧的字符确定。如果 itr 是一个数字,则左侧的所有连续数字都将视为非负起始值。右侧的所有连续数字都将视为比结束值大 1。

Indexed symbols can be defined using syntax similar to range() function. Ranges are indicated by a colon. Type of range is determined by the character to the right of the colon. If itr is a digit, all contiguous digits to the left are taken as the nonnegative starting value. All contiguous digits to the right are taken as 1 greater than the ending value.

>>> from sympy import symbols
>>> symbols('a:5')

上述片段的输出如下 −

The output of the above snippet is as follows −

(a0, a1, a2, a3, a4)

(a0, a1, a2, a3, a4)

>>> symbols('mark(1:4)')

上述片段的输出如下 −

The output of the above snippet is as follows −

(mark1, mark2, mark3)

(mark1, mark2, mark3)

SymPy - Substitution

对数学表达式执行的最基本操作之一是替换。SymPy 中的 subs() 函数将第一个参数的所有出现替换为第二个参数。

One of the most basic operations to be performed on a mathematical expression is substitution. The subs() function in SymPy replaces all occurrences of first parameter with second.

>>> from sympy.abc import x,a
>>> expr=sin(x)*sin(x)+cos(x)*cos(x)
>>> expr

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$\sin2(x)+\cos2(x)$

$\sin2(x)+\cos2(x)$

>>> expr.subs(x,a)

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$\sin2(a)+\cos2(a)$

$\sin2(a)+\cos2(a)$

如果我们想求某个表达式,此函数非常有用。例如,我们想通过用 5 替换 a 来计算以下表达式的值。

This function is useful if we want to evaluate a certain expression. For example, we want to calculate values of following expression by substituting a with 5.

>>> expr=a*a+2*a+5
>>> expr

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$a^2 + 2a + 5$

$a^2 + 2a + 5$

expr.subs(a,5)

上面的代码段给出了以下输出:

The above code snippet gives the following output −

40

40

>>> from sympy.abc import x
>>> from sympy import sin, pi
>>> expr=sin(x)
>>> expr1=expr.subs(x,pi)
>>> expr1

上面的代码段给出了以下输出:

The above code snippet gives the following output −

0

0

此函数还用于替换子表达式为另一个子表达式。在以下示例中,将 b 替换为 a+b。

This function is also used to replace a subexpression with another subexpression. In following example, b is replaced by a+b.

>>> from sympy.abc import a,b
>>> expr=(a+b)**2
>>> expr1=expr.subs(b,a+b)
>>> expr1

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$(2a + b)^2$

$(2a + b)^2$

SymPy - sympify() function

sympify() 函数用于转换任何任意表达式,这样它就可以用作 SymPy 表达式。整数对象等常规 Python 对象在 SymPy 中得到转换。整数等字符串也会转换为 SymPy 表达式。

The sympify() function is used to convert any arbitrary expression such that it can be used as a SymPy expression. Normal Python objects such as integer objects are converted in SymPy. Integer, etc.., strings are also converted to SymPy expressions.

>>> expr="x**2+3*x+2"
>>> expr1=sympify(expr)
>>> expr1
>>> expr1.subs(x,2)

上面的代码段给出了以下输出:

The above code snippet gives the following output −

12

12

任何 Python 对象都可以转换为 SymPy 对象。然而,由于转换在内部使用 eval() 函数,因此不应使用未经清理的表达式,否则会引发 SympifyError。

Any Python object can be converted in SymPy object. However, since the conversion internally uses eval() function, unsanitized expression should not be used, else SympifyError is raised.

>>> sympify("x***2")
---------------------------------------------------------------------------

SympifyError:表达式“无法解析’x***2'”的 Sympify 失败,因为引发了异常。

SympifyError: Sympify of expression 'could not parse 'x***2'' failed, because of exception being raised.

sympify() 函数采用如下参数:* strict:默认值为 False。如果设置为 True,则仅转换已为其定义显式转换的类型。否则,会引发 SympifyError。* evaluate:如果设置为 False,算术和运算符将转换为其 SymPy 等效项,而不会求值表达式。

The sympify() function takes following arguments: * strict: default is False. If set to True, only the types for which an explicit conversion has been defined are converted. Otherwise, SympifyError is raised. * evaluate: If set to False, arithmetic and operators will be converted into their SymPy equivalents without evaluating expression.

>>> sympify("10/5+4/2")

上面的代码段给出了以下输出:

The above code snippet gives the following output −

4

4

>>> sympify("10/5+4/2", evaluate=False)

上面的代码段给出了以下输出:

The above code snippet gives the following output −

$\frac{10}{5}+\frac{4}{2}$

$\frac{10}{5}+\frac{4}{2}$

SymPy - evalf() function

此函数会计算给定的数值表达式,其浮点精度最高为 100 位。此函数还使用 subs 参数获取符号的数值字典对象。考虑以下表达式

This function evaluates a given numerical expression upto a given floating point precision upto 100 digits. The function also takes subs parameter a dictionary object of numerical values for symbols. Consider following expression

>>> from sympy.abc import r
>>> expr=pi*r**2
>>> expr

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$\Pi{r^2}$

$\Pi{r^2}$

要使用 evalf() 函数求值以上表达式,请用 5 替换 r

To evaluate above expression using evalf() function by substituting r with 5

>>> expr.evalf(subs={r:5})

上面的代码段给出了以下输出:

The above code snippet gives the following output −

78.5398163397448

78.5398163397448

默认情况下,浮点精度最高为 15 位,可由 100 以内的任何数字覆盖。以下表达式的精度求值最高为 20 位。

By default, floating point precision is upto 15 digits which can be overridden by any number upto 100. Following expression is evaluated upto 20 digits of precision.

>>> expr=a/b
>>> expr.evalf(20, subs={a:100, b:3})

上面的代码段给出了以下输出:

The above code snippet gives the following output −

33.333333333333333333

33.333333333333333333

SymPy - Lambdify() function

lambdify 函数将 SymPy 表达式转换为 Python 函数。如果要在较大的值范围内求解表达式,则 evalf() 函数效率不高。lambdify 就像一个 lambda 函数,但它会将 SymPy 名称转换为给定数值库的名称,通常是 NumPy。默认情况下,lambdify 对 math 标准库中的实现进行操作。

The lambdify function translates SymPy expressions into Python functions. If an expression is to be evaluated over a large range of values, the evalf() function is not efficient. lambdify acts like a lambda function, except it converts the SymPy names to the names of the given numerical library, usually NumPy. By default, lambdify on implementations in the math standard library.

>>> expr=1/sin(x)
>>> f=lambdify(x, expr)
>>> f(3.14)

上面的代码段给出了以下输出:

The above code snippet gives the following output −

627.8831939138764

627.8831939138764

该表达式可能具有多个变量。在这种情况下,lambdify() 函数的第一个参数是变量列表,后跟要计算的表达式。

The expression might have more than one variables. In that case, first argument to lambdify() function is a list of variables, followed by the expression to be evaluated.

>>> expr=a**2+b**2
>>> f=lambdify([a,b],expr)
>>> f(2,3)

上面的代码段给出了以下输出:

The above code snippet gives the following output −

13

13

然而,要利用 numpy 库作为数值后端,我们必须将其定义为 lambdify() 函数的参数。

However, to leverage numpy library as numerical backend, we have to define the same as an argument for lambdify() function.

>>> f=lambdify([a,b],expr, "numpy")

我们在上述函数中为两个参数 a 和 b 使用了两个 numpy 数组。对于 numpy 数组,执行时间相当快。

We use two numpy arrays for two arguments a and b in the above function. The execution time is considerably fast in case of numpy arrays.

>>> import numpy
>>> l1=numpy.arange(1,6)
>>> l2=numpy.arange(6,11)
>>> f(l1,l2)

上面的代码段给出了以下输出:

The above code snippet gives the following output −

array([ 37, 53, 73, 97, 125], dtype=int32)

array([ 37, 53, 73, 97, 125], dtype=int32)

SymPy - Logical Expressions

布尔函数在 sympy.basic.booleanarg module 中定义。可以使用标准 python 运算符 &(And)、|(Or)、~(Not)以及 >> 和 << 来构建布尔表达式。布尔表达式继承自 SymPy 核心模块中定义的 Basic 类。

Boolean functions are defined in sympy.basic.booleanarg module. It is possible to build Boolean expressions with the standard python operators & (And), | (Or), ~ (Not) as well as with >> and <<. Boolean expressions inherit from Basic class defined in SymPy’s core module.

BooleanTrue function

此函数等效于核心 Python 中的 True。它返回一个单例,可以通过 S.true 检索。

This function is equivalent of True as in core Python. It returns a singleton that can be retrieved by S.true.

>>> from sympy import *
>>> x=sympify(true)
>>> x, S.true

上面的代码段给出了以下输出:

The above code snippet gives the following output −

(True, True)

BooleanFalse function

类似地,此函数等效于 Python 中的布尔 False,可以通过 S.false 访问。

Similarly, this function is equivalent to Boolean False in Python and can be accessed by S.false

>>> from sympy import *
>>> x=sympify(false)
>>> x, S.false

上面的代码段给出了以下输出:

The above code snippet gives the following output −

(False, False)

And function

逻辑 AND 函数对其两个参数求值,如果其中任何一个为 False,则返回 False。该函数模拟 & 运算符。

A logical AND function evaluates its two arguments and returns False if either of them is False. The function emulates & operator.

>>> from sympy import *
>>> from sympy.logic.boolalg import And
>>> x,y=symbols('x y')
>>> x=True
>>> y=True
>>> And(x,y), x"&"y

上面的代码段给出了以下输出:

The above code snippet gives the following output −

(True, True)

>>> y=False
>>> And(x,y), x"&"y

上面的代码段给出了以下输出:

The above code snippet gives the following output −

(False, False)

Or function

此函数对两个布尔参数求值,如果其中任何一个为 True,则返回 True。| 运算符方便地模拟其行为。

This function evaluates two Boolean arguments and returns True if either of them is True. The | operator conveniently emulates its behaviour.

>>> from sympy import *
>>> from sympy.logic.boolalg import Or
>>> x,y=symbols('x y')
>>> x=True
>>> y=False
>>> Or(x,y), x|y

上面的代码段给出了以下输出:

The above code snippet gives the following output −

(True, True)

>>> x=False
>>> y=False
>>> Or(x,y), x|y

上面的代码段给出了以下输出:

The above code snippet gives the following output −

(False, False)

Not Function

逻辑 Not 函数对布尔参数求反。如果其参数为 False,则返回 True;如果为 True,则返回 False。~ 运算符执行与 Not 函数类似的操作。如下例所示:

A Logical Not function results in negation of the Boolean argument. It returns True if its argument is False and returns False if True. The ~ operator performs the operation similar to Not function. It is shown in the example below −

>>> from sympy import *
>>> from sympy.logic.boolalg import Or, And, Not
>>> x,y=symbols('x y')
>>> x=True
>>> y=False
>>> Not(x), Not(y)

上面的代码段给出了以下输出:

The above code snippet gives the following output −

(False, True)

>>> Not(And(x,y)), Not(Or(x,y))

上面的代码段给出了以下输出:

The above code snippet gives the following output −

(True, False)

Xor Function

逻辑 XOR(异或)函数在奇数个参数为 True、其余参数为 False 时返回 True,在偶数个参数为 True、其余参数为 False 时返回 False。^ 运算符执行类似的操作。

The Logical XOR (exclusive OR) function returns True if an odd number of the arguments are True and the rest are False and returns False if an even number of the arguments are True and the rest are False. Similar operation is performed by ^ operator.

>>> from sympy import *
>>> from sympy.logic.boolalg import Xor
>>> x,y=symbols('x y')
>>> x=True
>>> y=False

>>> Xor(x,y), x^y

上面的代码段给出了以下输出:

The above code snippet gives the following output −

(True, True)

>>> a,b,c,d,e=symbols('a b c d e')
>>> a,b,c,d,e=(True, False, True, True, False)
>>> Xor(a,b,c,d,e)

上面的代码段给出了以下输出:

The above code snippet gives the following output −

True

在上述情况下,三个(奇数)参数为 True,因此 Xor 返回 true。但是,如果 True 参数的数量为偶数,则结果为 False,如下所示:

In above case, three (odd number) arguments are True, hence Xor returns true. However, if number of True arguments is even, it results in False, as shown below −

>>> a,b,c,d,e=(True, False, False, True, False)
>>> Xor(a,b,c,d,e)

上面的代码段给出了以下输出:

The above code snippet gives the following output −

False

Nand Function

此函数执行逻辑 NAND 操作。它对其参数求值,如果其中任何一个为 False,则返回 True,如果所有参数都为 True,则返回 False。

This function performs Logical NAND operation. It evaluates its arguments and returns True if any of them are False, and False if they are all True.

>>> from sympy import *
>>> from sympy.logic.boolalg import Nand
>>> a,b,c=symbols('a b c')
>>> a,b,c=(True, False, True)
>>> Nand(a,b,c), Nand(a,c)

上面的代码段给出了以下输出:

The above code snippet gives the following output −

(True, False)

Nor Function

此函数执行逻辑 NOR 操作。它对其参数求值,如果其中任何一个为 True,则返回 False,如果所有参数都为 False,则返回 True。

This function performs Logical NOR operation. It evaluates its arguments and returns False if any of them are True, and True if they are all False.

>>> from sympy import *
>>> from sympy.logic.boolalg import Nor
>>> a,b,c=symbols('a b c')
>>> a,b,c=(True, False, True)
>>> Nor(a,b,c), Nor(a,c)

上面的代码段给出了以下输出:

The above code snippet gives the following output −

(False, False)

需要注意的是,即使 SymPy 提供了 ^ 运算符用于 Xor,~ 用于 Not,| 用于 Or,& 用于 And 作为一种便利,但它们在 Python 中的常规用法是作为按位运算符。因此,如果操作数是整数,则结果不同。

Note that even though SymPy provides ^ operator for Xor, ~ for Not, | for Or and & for And functions as convenience, their normal use in Python is as bitwise operators. Hence, if operands are integers, results would be different.

Equivalent function

此函数返回等价关系。当且仅当 A 和 B 都是 True 或都是 False 时,Equivalent(A, B) 为 True。如果所有参数在逻辑上等效,则该函数返回 True。否则返回 False。

This function returns equivalence relation. Equivalent(A, B) is True if and only if A and B are both True or both False. The function returns True if all of the arguments are logically equivalent. Returns False otherwise.

>>> from sympy import *
>>> from sympy.logic.boolalg import Equivalent
>>> a,b,c=symbols('a b c')
>>> a,b,c=(True, False, True)
>>> Equivalent(a,b), Equivalent(a,c)

上面的代码段给出了以下输出:

The above code snippet gives the following output −

(False, True)

ITE function

此函数充当编程语言中的 If then else 子句。ITE(A, B, C) 求值并返回 B 的结果(如果 A 为真),否则返回 C 的结果。所有参数必须为布尔值。

This function acts as If then else clause in a programming language.ITE(A, B, C) evaluates and returns the result of B if A is true else it returns the result of C. All args must be Booleans.

>>> from sympy import * >>> from sympy.logic.boolalg import ITE >>> a,b,c=symbols('a b c') >>> a,b,c=(True, False, True)
>>> ITE(a,b,c), ITE(a,c,b)

上面的代码段给出了以下输出:

The above code snippet gives the following output −

(False, True)

SymPy - Querying

SymPy 程序包中的假设模块包含用于提取有关表达式的信息的工具。该模块为此目的定义了 ask() 函数。

The assumptions module in SymPy package contains tools for extracting information about expressions. The module defines ask() function for this purpose.

sympy.assumptions.ask(property)

以下属性提供了有关表达式的有用信息 −

Following properties provide useful information about an expression −

algebraic(x)

algebraic(x)

为了成为代数数,一个数必须是有理系数的非零多项式方程的根。√2 是代数数,因为 √2 是 x2 − 2 = 0 的解。

To be algebraic, a number must be a root of a non-zero polynomial equation with rational coefficients. √2 because √2 is a solution to x2 − 2 = 0, so it is algebraic.

complex(x)

complex(x)

复数谓词。当且仅当 x 属于复数集时,它为真。

Complex number predicate. It is true if and only if x belongs to the set of complex numbers.

composite(x)

composite(x)

ask(Q.composite(x)) 返回的复合数谓词当且仅当 x 为正整数,并且除了 1 和该数本身外,至少有一个正除数时为真。

Composite number predicate returned by ask(Q.composite(x)) is true if and only if x is a positive integer and has at least one positive divisor other than 1 and the number itself.

even, odd

even, odd

ask() 分别返回 x 在偶数集中和奇数集中的真值。

The ask() returns true of x is in the set of even numbers and set of odd numbers respectively.

imaginary

imaginary

此属性表示虚数谓词。当 x 可以表示为一个实数乘以虚数单位 I 时,它为真。

This property represents Imaginary number predicate. It is true if x can be written as a real number multiplied by the imaginary unit I.

integer

integer

Q.integer(x) 返回的此属性返回 x 属于偶数集的真值。

This property returned by Q.integer(x) returns true of x belong to set of even numbers.

rational, irrational

rational, irrational

Q.irrational(x)成立当且仅当 x 是任何不能表示为整数比的实数。例如,π 是一个无理数。

Q.irrational(x) is true if and only if x is any real number that cannot be expressed as a ratio of integers. For example, pi is an irrational number.

positive, negative

positive, negative

检查数字是正还是负的谓词

Predicates to check if number is positive or negative

zero, nonzero

zero, nonzero

检查数字是否为零的谓词

Predicates to heck if a number is zero or not

>>> from sympy import *
>>> x=Symbol('x')
>>> x=10
>>> ask(Q.algebraic(pi))
False
>>> ask(Q.complex(5-4*I)), ask( Q.complex(100))
(True, True)
>>> x,y=symbols("x y")
>>> x,y=5,10
>>> ask(Q.composite(x)), ask(Q.composite(y))
(False, True)
>>> ask(Q.even(x)), ask(Q.even(y))
(False, True)
>>> x,y= 2*I, 4+5*I
>>> ask(Q.imaginary(x)), ask(Q.imaginary(y))
(True, False)
>>> x,y=5,10
>>> ask(Q.even(x)), ask(Q.even(y)), ask(Q.odd(x)), ask(Q.odd(y))
(False, True, True, False)
>>> x,y=5,-5
>>> ask(Q.positive(x)), ask(Q.negative(y)), ask(Q.positive(x)), ask(Q.negative(y))
(True, True, True, True)
>>> ask(Q.rational(pi)), ask(Q.irrational(S(2)/3))
(False, False)
>>> ask(Q.zero(oo)), ask(Q.nonzero(I))
(False, False)

SymPy - Simplification

Sympy 有强大的数学表达式简化能力。SymPy 中有许多函数可执行各种类型的化简。有一个称为 simplify() 的通用函数,它尝试到达表达式的最简单形式。

Sympy has powerful ability to simplify mathematical expressions. There are many functions in SymPy to perform various kinds of simplification. A general function called simplify() is there that attempts to arrive at the simplest form of an expression.

simplify

此函数在 sympy.simplify 模块中定义。simplify() 尝试应用智能启发式来使输入表达式“更简单”。以下代码显示了表达式 $sin 2(x)+cos 2(x)$ 的简化形式。

This function is defined in sympy.simplify module. simplify() tries to apply intelligent heuristics to make the input expression “simpler”. Following code shows simplifies expression $sin2(x)+cos2(x)$.

>>> from sympy import *
>>> x=Symbol('x')
>>> expr=sin(x)**2 + cos(x)**2
>>> simplify(expr)

上面的代码段给出了以下输出:

The above code snippet gives the following output −

1

1

expand

expand() 是 SymPy 中最常见的简化函数之一,用于展开多项式表达式。例如:

The expand() is one of the most common simplification functions in SymPy, used in expanding polynomial expressions. For example −

>>> a,b=symbols('a b')
>>> expand((a+b)**2)

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$a^2 + 2ab + b^2$

$a^2 + 2ab + b^2$

>>> expand((a+b)*(a-b))

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$a^2 - b^2$

$a^2 - b^2$

expand() 函数使表达式变大,而不是变小。通常情况下是这样,但expand() 经常会让表达式变小。

The expand() function makes expressions bigger, not smaller. Usually this is the case, but often an expression will become smaller upon calling expand() on it.

>>> expand((x + 1)*(x - 2) - (x - 1)*x)

上面的代码段给出了以下输出:

The above code snippet gives the following output −

-2

-2

factor

此函数采用一个多项式,并将其分解为有理数上的不可约因子。

This function takes a polynomial and factors it into irreducible factors over the rational numbers.

>>> x,y,z=symbols('x y z')
>>> expr=(x**2*z + 4*x*y*z + 4*y**2*z)
>>> factor(expr)

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$z(x + 2y)^2$

$z(x + 2y)^2$

>>> factor(x**2+2*x+1)

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$(x + 1)^2$

$(x + 1)^2$

factor() 函数是 expand() 的相反函数。 factor() 返回的每个因子都保证是不可约的。 factor_list() 函数会返还更具结构的输出。

The factor() function is the opposite of expand(). Each of the factors returned by factor() is guaranteed to be irreducible. The factor_list() function returns a more structured output.

>>> expr=(x**2*z + 4*x*y*z + 4*y**2*z)
>>> factor_list(expr)

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

(1, [(z, 1), (x + 2*y, 2)])

(1, [(z, 1), (x + 2*y, 2)])

collect

此函数收集表达式中的加法项,根据含有有理指数的表达式列表分项。

This function collects additve terms of an expression with respect to a list of expression up to powers with rational exponents.

>>> expr=x*y + x - 3 + 2*x**2 - z*x**2 + x**3
>>> expr

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$x^3 + x^2z + 2x^2 + xy + x - 3$

$x^3 + x^2z + 2x^2 + xy + x - 3$

针对这个表达式,collect() 函数的结果如下 −

The collect() function on this expression results as follows −

>>> collect(expr,x)

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$x^3 + x^2(2 - z) + x(y + 1) - 3$

$x^3 + x^2(2 - z) + x(y + 1) - 3$

>>> expr=y**2*x + 4*x*y*z + 4*y**2*z+y**3+2*x*y
>>> collect(expr,y)

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$Y3+Y2(x+4z)+y(4xz+2x)$

$Y3+Y2(x+4z)+y(4xz+2x)$

cancel

cancel() 函数接受任意有理函数,并将其化成标准规范形式,p/q,其中 p 和 q 是没有公因子的展开多项式。p 和 q 的前导系数没有分母,即它们是整数。

The cancel() function will take any rational function and put it into the standard canonical form, p/q, where p and q are expanded polynomials with no common factors. The leading coefficients of p and q do not have denominators i.e., they are integers.

>>> expr1=x**2+2*x+1
>>> expr2=x+1
>>> cancel(expr1/expr2)

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$x+1$

$x+1$

>>> expr = 1/x + (3*x/2 - 2)/(x - 4)
>>> expr

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$\frac{\frac{3x}{2} - 2}{x - 4} + \frac{1}{x}$

$\frac{\frac{3x}{2} - 2}{x - 4} + \frac{1}{x}$

>>> cancel(expr)

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$\frac{3x^2 - 2x - 8}{2x^2 - 8}$

$\frac{3x^2 - 2x - 8}{2x^2 - 8}$

>>> expr=1/sin(x)**2
>>> expr1=sin(x)
>>> cancel(expr1*expr)

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$\frac{1}{\sin(x)}$

$\frac{1}{\sin(x)}$

trigsimp

此函数用于化简三角恒等式。需要注意的是,反三角函数的命名规则是将 a 附在函数名的前面。例如,反余弦或余弦弧称为 acos()。

This function is used to simplify trigonometric identities. It may be noted that naming conventions for inverse trigonometric functions is to append an a to the front of the function’s name. For example, the inverse cosine, or arc cosine, is called acos().

>>> from sympy import trigsimp, sin, cos
>>> from sympy.abc import x, y
>>> expr = 2*sin(x)**2 + 2*cos(x)**2
>>> trigsimp(expr)

2

2

trigsimp 函数使用启发式方法来应用最合适三角恒等式。

The trigsimp function uses heuristics to apply the best suitable trigonometric identity.

powersimp

此函数通过将具有类似底数和指数的幂结合起来,来化简给定的表达式。

This function reduces given expression by combining powers with similar bases and exponents.

>>> expr=x**y*x**z*y**z
>>> expr

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$x^y x^z y^z$

$x^y x^z y^z$

>>> powsimp(expr)

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$x^{y+z} y^z$

$x^{y+z} y^z$

可以通过改变 combine=’base’ 或 combine=’exp’ 来使 powsimp() 仅合并底数或仅合并指数。默认情况下,combine=’all’,它同时执行这两个操作。如果 force 为 True,则会在不检查假设的情况下合并底数。

You can make powsimp() only combine bases or only combine exponents by changing combine=’base’ or combine=’exp’. By default, combine=’all’, which does both.If force is True then bases will be combined without checking for assumptions.

>>> powsimp(expr, combine='base', force=True)

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$xy(xy)z$

$xy(xy)z$

combsimp

涉及阶乘和二项式的组合表达式可使用 combsimp() 函数进行化简。SymPy 提供了一个 factorial() 函数

Combinatorial expressions involving factorial an binomials can be simplified by using combsimp() function. SymPy provides a factorial() function

>>> expr=factorial(x)/factorial(x - 3)
>>> expr

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$\frac{x!}{(x - 3)!}$

$\frac{x!}{(x - 3)!}$

为了化简上述组合表达式,我们使用 combsimp() 函数,如下所示:

To simplify above combinatorial expression we use combsimp() function as follows −

>>> combsimp(expr)

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$x(x-2)(x-1)$

$x(x-2)(x-1)$

二项式 (x, y) 是从一组 x 个不同的项目中选择 y 个项目的方法的数量。通常也写为 xCy。

The binomial(x, y) is the number of ways to choose y items from a set of x distinct items. It is also often written as xCy.

>>> binomial(x,y)

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$(\frac{x}{y})$

$(\frac{x}{y})$

>>> combsimp(binomial(x+1, y+1)/binomial(x, y))

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$\frac{x + 1}{y + 1}$

$\frac{x + 1}{y + 1}$

logcombine

此函数取对数并将它们使用以下规则进行合并:

This function takes logarithms and combines them using the following rules −

  1. log(x) + log(y) == log(x*y) if both are positive

  2. a*log(x) == log(x**a) if x is positive and a is real

>>> logcombine(a*log(x) + log(y) - log(z))

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$a\log(x) + \log(y) - \log(z)$

$a\log(x) + \log(y) - \log(z)$

如果此函数的 force 参数设置为 True,则如果在某个量上还没有假设,则将假定上述假设成立。

If force parameter of this function is set to True then the assumptions above will be assumed to hold if there is no assumption already in place on a quantity.

>>> logcombine(a*log(x) + log(y) - log(z), force=True)

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$\log\frac{x^a y}{z}$

$\log\frac{x^a y}{z}$

SymPy - Derivative

函数的导数是指它相对于其一个变量的瞬时变化率。这相当于找到该函数在某一点的切线斜率。我们能够使用 SymPy 包中的 diff() 函数找到以变量形式表示的数学表达式的微分。

The derivative of a function is its instantaneous rate of change with respect to one of its variables. This is equivalent to finding the slope of the tangent line to the function at a point.we can find the differentiation of mathematical expressions in the form of variables by using diff() function in SymPy package.

diff(expr, variable)
>>> from sympy import diff, sin, exp
>>> from sympy.abc import x,y
>>> expr=x*sin(x*x)+1 >>> expr

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$x\sin(x^2) + 1$

$x\sin(x^2) + 1$

>>> diff(expr,x)

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$2x2\cos(x2) + \sin(x^2)$

$2x2\cos(x2) + \sin(x^2)$

>>> diff(exp(x**2),x)

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

2xex2

2xex2

若要获取多个导数,按照需要求导的次数传递变量,或在变量后传递一个数字。

To take multiple derivatives, pass the variable as many times as you wish to differentiate, or pass a number after the variable.

>>> diff(x**4,x,3)

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$24x$

$24x$

>>> for i in range(1,4): print (diff(x**4,x,i))

上面的代码段给出了以下表达式:

The above code snippet gives the below expression −

4*x 3

4*x*3*

12*x 2

12*x*2*

24*x

24*x

也可以调用表达式的 diff() 方法。它的工作方式与 diff() 函数类似。

It is also possible to call diff() method of an expression. It works similarly as diff() function.

>>> expr=x*sin(x*x)+1
>>> expr.diff(x)

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$2x2\cos(x2) + \sin(x^2)$

$2x2\cos(x2) + \sin(x^2)$

使用 Derivative 类可以创建一个未求值的导数。它的语法与 diff() 函数相同。若要求一个未求值的导数,请使用 doit 方法。

An unevaluated derivative is created by using the Derivative class. It has the same syntax as diff() function. To evaluate an unevaluated derivative, use the doit method.

>>> from sympy import Derivative
>>> d=Derivative(expr)
>>> d

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$\frac{d}{dx}(x\sin(x^2)+1)$

$\frac{d}{dx}(x\sin(x^2)+1)$

>>> d.doit()

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$2x2\cos(x2) + \sin(x^2)$

$2x2\cos(x2) + \sin(x^2)$

SymPy - Integration

SymPy 程序包包含 integrals 模块。它实现计算表达式的定积分和不定积分的方法。integrate() 方法用于计算定积分和不定积分。要计算不定积分或原始积分,只须在表达式后面传递变量。

The SymPy package contains integrals module. It implements methods to calculate definite and indefinite integrals of expressions. The integrate() method is used to compute both definite and indefinite integrals. To compute an indefinite or primitive integral, just pass the variable after the expression.

例如 -

For example −

integrate(f, x)

若要计算定积分,请按如下所示传递参数 -

To compute a definite integral, pass the argument as follows −

(integration_variable, lower_limit, upper_limit)
>>> from sympy import *
>>> x,y = symbols('x y')
>>> expr=x**2 + x + 1
>>> integrate(expr, x)

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$\frac{x^3}{3} + \frac{x^2}{2} + x$

$\frac{x^3}{3} + \frac{x^2}{2} + x$

>>> expr=sin(x)*tan(x)
>>> expr
>>> integrate(expr,x)

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$-\frac{\log(\sin(x) - 1)}{2} + \frac{\log(\sin(x) + 1)}{2} - \sin(x)$

$-\frac{\log(\sin(x) - 1)}{2} + \frac{\log(\sin(x) + 1)}{2} - \sin(x)$

以下是定积分的示例 -

The example of definite integral is given below −

>>> expr=exp(-x**2)
>>> integrate(expr,(x,0,oo) )

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$\frac{\sqrt\pi}{2}$

$\frac{\sqrt\pi}{2}$

你可以传递多个限制元组来执行定积分。以下是示例 -

You can pass multiple limit tuples to perform a multiple integral. An example is given below −

>>> expr=exp(-x**2 - y**2)
>>> integrate(expr,(x,0,oo),(y,0,oo))

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$\frac{\pi}{4}$

$\frac{\pi}{4}$

你可以使用 Integral 对象创建未计算的积分,而 Integral 对象可以通过调用 doit() 方法来计算。

You can create unevaluated integral using Integral object, which can be evaluated by calling doit() method.

>>> expr = Integral(log(x)**2, x)
>>> expr

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$\int \mathrm\log(x)^2 \mathrm{d}x$

$\int \mathrm\log(x)^2 \mathrm{d}x$

>>> expr.doit()

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$x\log(x)^2 - 2xlog(x) + 2x$

$x\log(x)^2 - 2xlog(x) + 2x$

Integral Transforms

SymPy 支持各种类型的积分变换,如下所示 -

SymPy supports various types of integral transforms as follows −

  1. laplace_transform

  2. fourier_transform

  3. sine_transform

  4. cosine_transform

  5. hankel_transform

这些函数在 sympy.integrals.transforms 模块中定义。下列示例分别为计算傅里叶变换和拉普拉斯变换。

These functions are defined in sympy.integrals.transforms module. Following examples compute Fourier transform and Laplace transform respectively.

Example 1

Example 1

>>> from sympy import fourier_transform, exp
>>> from sympy.abc import x, k
>>> expr=exp(-x**2)
>>> fourier_transform(expr, x, k)

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

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

sqrt(pi)*exp(-pi**2*k**2)

等效于 -

Which is equivalent to −

$\sqrt\pi * e{\pi2k^2}$

$\sqrt\pi * e{\pi2k^2}$

Example 2

Example 2

>>> from sympy.integrals import laplace_transform
>>> from sympy.abc import t, s, a
>>> laplace_transform(t**a, t, s)

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

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

(s**(-a)*gamma(a + 1)/s, 0, re(a) > -1)

SymPy - Matrices

在数学中,矩阵是二维数字、符号或表达式的数组。矩阵操作的理论涉及对矩阵目标执行算术操作,但要遵循特定规则。

In Mathematics, a matrix is a two dimensional array of numbers, symbols or expressions. Theory of matrix manipulation deals with performing arithmetic operations on matrix objects, subject to certain rules.

线性变换是矩阵的重要应用之一。许多科学领域,特别是与物理学相关的领域,都使用与矩阵相关的应用程序。

Linear transformation is one of the important applications of matrices. Many scientific fields, specially related to Physics use matrix related applications.

SymPy 包具有处理矩阵的 matrices 模块。他包含 Matrix 类,其对象表示一个矩阵。

SymPy package has matrices module that deals with matrix handling. It includes Matrix class whose object represents a matrix.

Note: If you want to execute all the snippets in this chapter individually, you need to import the matrix module as shown below −

Note: If you want to execute all the snippets in this chapter individually, you need to import the matrix module as shown below −

>>> from sympy.matrices import Matrix

Example

>>> from sympy.matrices import Matrix
>>> m=Matrix([[1,2,3],[2,3,1]])
>>> m
$\displaystyle \left[\begin{matrix}1 & 2 & 3\\2 & 3 & 1\end{matrix}\right]$

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

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

[1 2 3 2 3 1]

[1 2 3 2 3 1]

可以使用大小合适的 List 对象创建矩阵。也可以通过按指定行数和列数分配列表项来获取矩阵。

Matrix is created from appropriately sized List objects. You can also obtain a matrix by distributing list items in specified number of rows and columns.

>>> M=Matrix(2,3,[10,40,30,2,6,9])
>>> M
$\displaystyle \left[\begin{matrix}10 & 40 & 30\\2 & 6 & 9\end{matrix}\right]$

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

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

[10 40 30 2 6 9]

[10 40 30 2 6 9]

矩阵是一个可变对象。matrices 模块还提供 ImmutableMatrix 类来获取不可变矩阵。

Matrix is a mutable object. The matrices module also provides ImmutableMatrix class for obtaining immutable matrix.

Basic manipulation

Matrix 对象的 shape 属性返回其大小。

The shape property of Matrix object returns its size.

>>> M.shape

以上代码的输出如下 −

The output for the above code is as follows −

(2,3)

(2,3)

row() 和 col() 方法分别返回指定数量的行或列。

The row() and col() method respectively returns row or column of specified number.

>>> M.row(0)
$\displaystyle \left[\begin{matrix}10 & 40 & 30\end{matrix}\right]$

以上代码的输出如下 −

The output for the above code is as follows −

[10 40 30]

[10 40 30]

>>> M.col(1)
$\displaystyle \left[\begin{matrix}40\\6\end{matrix}\right]$

以上代码的输出如下 −

The output for the above code is as follows −

[40 6]

[40 6]

可以使用 Python 的切片操作符获取属于行或列的一个或多个项。

Use Python’s slice operator to fetch one or more items belonging to row or column.

>>> M.row(1)[1:3]
[6, 9]

Matrix 类具有 row_del() 和 col_del() 方法,用于从给定矩阵中删除指定行/列,如下所示:

Matrix class has row_del() and col_del() methods that deletes specified row/column from given matrix −

>>> M=Matrix(2,3,[10,40,30,2,6,9])
>>> M.col_del(1)
>>> M

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

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

Matrix([[10, 30],[ 2, 9]])

可以使用以下命令给输出应用样式:

You can apply style to the output using the following command −

$\displaystyle \left[\begin{matrix}10 & 30\\2 & 9\end{matrix}\right]$

执行以上代码片段后,可以获得以下输出:

You get the following output after executing the above code snippet −

[10 30 2 9]

[10 30 2 9]

>>> M.row_del(0)
>>> M

$\displaystyle \left[\begin{matrix}2 & 9\end{matrix}\right]$

执行以上代码片段后,可以获得以下输出:

You get the following output after executing the above code snippet −

[2 9]

[2 9]

同样,row_insert() 和 col_insert() 方法在指定行或列索引处添加行或列

Similarly, row_insert() and col_insert() methods add rows or columns at specified row or column index

>>> M1=Matrix([[10,30]])
>>> M=M.row_insert(0,M1)
>>> M

$\displaystyle \left[\begin{matrix}10 & 30\\2 & 9\end{matrix}\right]$

执行以上代码片段后,可以获得以下输出:

You get the following output after executing the above code snippet −

[10 40 30 2 9]

[10 40 30 2 9]

>>> M2=Matrix([40,6])
>>> M=M.col_insert(1,M2)
>>> M

$\displaystyle \left[\begin{matrix}10 & 40 & 30\\2 & 6 & 9\end{matrix}\right]$

执行以上代码片段后,可以获得以下输出:

You get the following output after executing the above code snippet −

[10 40 30 6 9]

[10 40 30 6 9]

Arithmetic Operations

通常的操作符 + 、 - 和 * 被定义为执行加法、减法和乘法运算。

Usual operators +, - and * are defined for performing addition, subtraction and multiplication.

>>> M1=Matrix([[1,2,3],[3,2,1]])
>>> M2=Matrix([[4,5,6],[6,5,4]])
>>> M1+M2

$\displaystyle \left[\begin{matrix}5 & 7 & 9\\9 & 7 & 5\end{matrix}\right]$

执行以上代码片段后,可以获得以下输出:

You get the following output after executing the above code snippet −

[5 7 9 9 7 5]

[5 7 9 9 7 5]

>>> M1-M2
$\displaystyle \left[\begin{matrix}-3 & -3 & -3\\-3 & -3 & -3\end{matrix}\right]$

执行以上代码片段后,可以获得以下输出:

You get the following output after executing the above code snippet −

[- 3 -3 -3 -3 -3 -3]

[- 3 -3 -3 -3 -3 -3]

矩阵乘法只有在以下情况下才可能:- 第一个矩阵的列数必须等于第二个矩阵的行数。- 结果的行数将和第一个矩阵相同,列数将和第二个矩阵相同。

Matrix multiplication is possible only if - The number of columns of the 1st matrix must equal the number of rows of the 2nd matrix. - And the result will have the same number of rows as the 1st matrix, and the same number of columns as the 2nd matrix.

>>> M1=Matrix([[1,2,3],[3,2,1]])
>>> M2=Matrix([[4,5],[6,6],[5,4]])
>>> M1*M2
$\displaystyle \left[\begin{matrix}31 & 29\\29 & 31\end{matrix}\right]$

以上代码的输出如下 −

The output for the above code is as follows −

[31 29 29 31]

[31 29 29 31]

>>> M1.T
$\displaystyle \left[\begin{matrix}1 & 3\\2 & 2\\3 & 1\end{matrix}\right]$

在执行代码 − 之后,将得到以下输出:

The following output is obtained after executing the code −

[1 3 2 2 3 1]

[1 3 2 2 3 1]

要计算矩阵的行列式,请使用 det() 方法。行列式是一个标量值,可以从方阵的元素计算得出。0

To calculate a determinant of matrix, use det() method. A determinant is a scalar value that can be computed from the elements of a square matrix.0

>>> M=Matrix(3,3,[10,20,30,5,8,12,9,6,15])
>>> M
$\displaystyle \left[\begin{matrix}10 & 20 & 30\\5 & 8 & 12\\9 & 6 & 15\end{matrix}\right]$

以上代码的输出如下 −

The output for the above code is as follows −

[10 20 30 5 8 12 9 6 15]

[10 20 30 5 8 12 9 6 15]

>>> M.det()

以上代码的输出如下 −

The output for the above code is as follows −

-120

-120

Matrix Constructors

SymPy 提供了许多特殊类型的矩阵类。例如,单位矩阵、由所有零和一组成的矩阵等。这些类分别命名为 eye、zeros 和 ones。单位矩阵是一个方阵,对角线上的元素设置为 1,其余元素均为 0。

SymPy provides many special type of matrix classes. For example, Identity matrix, matrix of all zeroes and ones, etc. These classes are named as eye, zeros and ones respectively. Identity matrix is a square matrix with elements falling on diagonal are set to 1, rest of the elements are 0.

Example

from sympy.matrices import eye eye(3)

Output

Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
$\displaystyle \left[\begin{matrix}1 & 0 & 0\\0 & 1 & 0\\0 & 0 & 1\end{matrix}\right]$

以上代码的输出如下 −

The output for the above code is as follows −

[1 0 0 0 1 0 0 0 1]

[1 0 0 0 1 0 0 0 1]

在 diag 矩阵中,对角线上的元素根据提供参数来初始化。

In diag matrix, elements on diagonal are initialized as per arguments provided.

>>> from sympy.matrices import diag
>>> diag(1,2,3)

$\displaystyle \left[\begin{matrix}1 & 0 & 0\\0 & 2 & 0\\0 & 0 & 3\end{matrix}\right]$

以上代码的输出如下 −

The output for the above code is as follows −

[1 0 0 0 2 0 0 0 3]

[1 0 0 0 2 0 0 0 3]

在 zeros 矩阵中,所有元素都初始化为 0。

All elements in zeros matrix are initialized to 0.

>>> from sympy.matrices import zeros
>>> zeros(2,3)

$\displaystyle \left[\begin{matrix}0 & 0 & 0\\0 & 0 & 0\end{matrix}\right]$

以上代码的输出如下 −

The output for the above code is as follows −

[0 0 0 0 0 0]

[0 0 0 0 0 0]

类似地,ones 是一个矩阵,其中的所有元素都设置为 1。

Similarly, ones is matrix with all elements set to 1.

>>> from sympy.matrices import ones
>>> ones(2,3)

$\displaystyle \left[\begin{matrix}1 & 1 & 1\\1 & 1 & 1\end{matrix}\right]$

以上代码的输出如下 −

The output for the above code is as follows −

[1 1 1 1 1 1]

[1 1 1 1 1 1]

SymPy - Function class

Sympy 包具有 Function 类,该类在 sympy.core.function 模块中定义。它是一个基类,适用于所有应用的数学函数,也是未定义函数类的构造函数。

Sympy package has Function class, which is defined in sympy.core.function module. It is a base class for all applied mathematical functions, as also a constructor for undefined function classes.

以下类别的函数从 Function 类继承 −

Following categories of functions are inherited from Function class −

  1. Functions for complex number

  2. Trigonometric functions

  3. Functions for integer number

  4. Combinatorial functions

  5. Other miscellaneous functions

Functions for complex number

这组函数在 sympy.functions.elementary.complexes 模块中定义。

This set of functions is defined in sympy.functions.elementary.complexes module.

re

re

此函数返回表达式的实部 −

This function returns real part of an expression −

>>> from sympy import *
>>> re(5+3*I)

以上代码片段的输出如下所示 −

The output for the above code snippet is given below −

5

5

>>> re(I)

以上代码片段的输出为 −

The output for the above code snippet is −

0

0

Im

Im

此函数返回表达式的虚部 −

This function returns imaginary part of an expression −

>>> im(5+3*I)

以上代码片段的输出如下所示 −

The output for the above code snippet is given below −

3

3

>>> im(I)

以上代码片段的输出如下所示 −

The output for the above code snippet is given below −

1

1

sign

sign

此函数返回表达式的复数标志。

This function returns the complex sign of an expression.

对于实部表达式,标志将为 −

For real expression, the sign will be −

  1. 1 if expression is positive

  2. 0 if expression is equal to zero

  3. -1 if expression is negative

如果表达式为虚部,返回的标志为 −

If expression is imaginary the sign returned is −

  1. I if im(expression) is positive

  2. -I if im(expression) is negative

>>> sign(1.55), sign(-1), sign(S.Zero)

以上代码片段的输出如下所示 −

The output for the above code snippet is given below −

(1, -1, 0)

(1, -1, 0)

>>> sign (-3*I), sign(I*2)

以上代码片段的输出如下所示 −

The output for the above code snippet is given below −

(-I, I)

(-I, I)

Abs

Abs

此函数返回复数的绝对值。它定义为复平面中原点 (0,0) 和点 (a,b) 之间的距离。此函数是内置函数 abs() 的扩展,以接受符号值。

This function return absolute value of a complex number. It is defined as the distance between the origin (0,0) and the point (a,b) in the complex plane. This function is an extension of the built-in function abs() to accept symbolic values.

>>> Abs(2+3*I)

以上代码片段的输出如下所示 −

The output for the above code snippet is given below −

$\sqrt13$

$\sqrt13$

conjugate

conjugate

此函数返回复数的共轭。要找到复共轭,我们更改虚部的符号。

This function returns conjugate of a complex number. To find the complex conjugate we change the sign of the imaginary part.

>>> conjugate(4+7*I)

执行以上代码片段后,可以获得以下输出:

You get the following output after executing the above code snippet −

4 - 7i

4 - 7i

Trigonometric functions

SymPy 已定义所有三角比——sin cos、tan 等以及其逆如 asin、acos、atan 等。这些函数计算用弧度表示的给定角度的相应值。

SymPy has defintions for all trigonometric ratios - sin cos, tan etc as well as well as its inverse counterparts such as asin, acos, atan etc. These functions compute respective value for given angle expressed in radians.

>>> sin(pi/2), cos(pi/4), tan(pi/6)

以上代码片段的输出如下所示 −

The output for the above code snippet is given below −

(1, sqrt(2)/2, sqrt(3)/3)

(1, sqrt(2)/2, sqrt(3)/3)

>>> asin(1), acos(sqrt(2)/2), atan(sqrt(3)/3)

以上代码片段的输出如下所示 −

The output for the above code snippet is given below −

(pi/2, pi/4, pi/6)

(pi/2, pi/4, pi/6)

Functions on Integer Number

这是一组在整数上执行各种操作的函数。

This is a set of functions to perform various operations on integer number.

ceiling

ceiling

这是一个单变量函数,它返回不小于其参数的最小整数值。对于复数,分别对实部和虚部取上整。

This is a univariate function which returns the smallest integer value not less than its argument. In case of complex numbers, ceiling of the real and imaginary parts separately.

>>> ceiling(pi), ceiling(Rational(20,3)), ceiling(2.6+3.3*I)

以上代码片段的输出如下所示 −

The output for the above code snippet is given below −

(4, 7, 3 + 4*I)

(4, 7, 3 + 4*I)

floor

floor

此函数返回不大小于其参数的最大整数值。对于复数,此函数也分别对实部和虚部取下整。

This function returns the largest integer value not greater than its argument. In case of complex numbers, this function too takes the floor of the real and imaginary parts separately.

>>> floor(pi), floor(Rational(100,6)), floor(6.3-5.9*I)

以上代码片段的输出如下所示 −

The output for the above code snippet is given below −

(3, 16, 6 - 6*I)

(3, 16, 6 - 6*I)

frac

frac

此函数表示 x 的小数部分。

This function represents the fractional part of x.

>>> frac(3.99), frac(Rational(10,3)), frac(10)

以上代码片段的输出如下所示 −

The output for the above code snippet is given below −

(0.990000000000000, 1/3, 0)

(0.990000000000000, 1/3, 0)

Combinatorial functions

组合学是一个数学领域,涉及有限或离散系统中的选择、排列和运算问题。

Combinatorics is a field of mathematics concerned with problems of selection, arrangement, and operation within a finite or discrete system.

factorial

factorial

阶乘在组合学中非常重要,它给出了 n 个对象可以进行排列的方式的数量。它以符号形式表示为 ð ‘¥!此函数是对非负整数的阶乘函数的实现,负整数的阶乘是复数无穷大。

The factorial is very important in combinatorics where it gives the number of ways in which n objects can be permuted. It is symbolically represented as 𝑥! This function is implementation of factorial function over nonnegative integers, factorial of a negative integer is complex infinity.

>>> x=Symbol('x')
>>> factorial(x)

以上代码片段的输出如下所示 −

The output for the above code snippet is given below −

x!

x!

>>> factorial(5)

以上代码片段的输出如下所示 −

The output for the above code snippet is given below −

120

120

>>> factorial(-1)

以上代码片段的输出如下所示 −

The output for the above code snippet is given below −

$\infty\backsim$

$\infty\backsim$

binomial

此函数给出了从 n 个元素的集合中选择 k 个元素的方式的数量。

This function the number of ways we can choose k elements from a set of n elements.

>>> x,y=symbols('x y')
>>> binomial(x,y)

以上代码片段的输出如下所示 −

The output for the above code snippet is given below −

$(\frac{x}{y})$

$(\frac{x}{y})$

>>> binomial(4,2)

以上代码片段的输出如下所示 −

The output for the above code snippet is given below −

6

6

帕斯卡三角形的行可以使用二项式函数生成。

Rows of Pascal’s triangle can be generated with the binomial function.

>>> for i in range(5): print ([binomial(i,j) for j in range(i+1)])

执行以上代码片段后,可以获得以下输出:

You get the following output after executing the above code snippet −

[1]

[1]

[1, 1]

[1, 1]

[1, 2, 1]

[1, 2, 1]

[1, 3, 3, 1]

[1, 3, 3, 1]

[1, 4, 6, 4, 1]

[1, 4, 6, 4, 1]

fibonacci

fibonacci

斐波那契数是由初始项 F0=0、F1=1 和二项递归关系 Fn=Fn−1+Fn−2 定义的整数序列。

The Fibonacci numbers are the integer sequence defined by the initial terms F0=0, F1=1 and the two-term recurrence relation Fn=Fn−1+Fn−2.

>>> [fibonacci(x) for x in range(10)]

执行上面的代码片段后获得以下输出 −

The following output is obtained after executing the above code snippet −

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

tribonacci

tribonacci

Tribonacci 数列是由初始项 F0=0、F1=1、F2=1 和三项循环关系式 Fn=Fn-1+Fn-2+Fn-3 定义的整数序列。

The Tribonacci numbers are the integer sequence defined by the initial terms F0=0, F1=1, F2=1 and the three-term recurrence relation Fn=Fn-1+Fn-2+Fn-3.

>>> tribonacci(5, Symbol('x'))

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$x^8 + 3x^5 + 3x^2$

$x^8 + 3x^5 + 3x^2$

>>> [tribonacci(x) for x in range(10)]

执行上面的代码片段后获得以下输出 −

The following output is obtained after executing the above code snippet −

[0, 1, 1, 2, 4, 7, 13, 24, 44, 81]

[0, 1, 1, 2, 4, 7, 13, 24, 44, 81]

Miscellaneous Functions

以下是一些常用函数的列表 −

Following is a list of some frequently used functions −

Min − 返回列表的最小值。它命名为 Min 以避免与内置函数 min 冲突。

Min − Returns minimum value of the list. It is named Min to avoid conflicts with the built-in function min.

Max − 返回列表的最大值。它命名为 Max 以避免与内置函数 max 冲突。

Max − Returns maximum value of the list. It is named Max to avoid conflicts with the built-in function max.

root − 返回 x 的 n 次方根。

root − Returns nth root of x.

sqrt − 返回 x 的主平方根。

sqrt − Returns the principal square root of x.

cbrt − 此函数计算 x 的主立方根(x++Rational(1,3) 的快捷方式)。

cbrt − This function computes the principal cube root of x, (shortcut for x++Rational(1,3)).

以下是以上杂项函数及其各自输出的示例 −

The following are the examples of the above miscellaneous functions and their respective outputs −

>>> Min(pi,E)

e

e

>>> Max(5, Rational(11,2))

$\frac{11}{2}$

$\frac{11}{2}$

>>> root(7,Rational(1,2))

49

49

>>> sqrt(2)

$\sqrt2$

$\sqrt2$

>>> cbrt(1000)

10

10

SymPy - Quaternion

在数学中,四元数数系是由复数扩展得来的。每个四元数对象包含四个标量变量和四个维度,一个实数维度和三个虚数维度。

In mathematics, Quaternion number system is an extension of complex numbers. Each Quaternion object contains four scalar variables and four dimensions, one real dimension and three imaginary dimensions.

四元数由以下表达式表示 −

Quaternion is represented by following expression −

q=a+bi+cj+dk

其中 a, b, c 和 d 是实数, i, j, k 是四元数单位,使得 i2==j2==k2==ijk

where a, b, c and d are real numbers and i, j, k are quaternion units such that,i2==j2==k2==ijk

sympy.algebras.quaternion 模块有四元数类。

The sympy.algebras.quaternion module has Quaternion class.

>>> from sympy.algebras.quaternion import Quaternion
>>> q=Quaternion(2,3,1,4)
>>> q

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$2 + 3i + 1j + 4k$

$2 + 3i + 1j + 4k$

四元数用于纯数学中,以及应用数学、计算机图形、计算机视觉中,等等。

Quaternions are used in pure mathematics, as well as in applied mathematics, computer graphics, computer vision, etc.

>>> from sympy import *
>>> x=Symbol('x')
>>> q1=Quaternion(x**2, x**3, x) >>> q1

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$x^2 + x^3i + xj + 0k$

$x^2 + x^3i + xj + 0k$

四元数对象还可以具有虚系数

Quaternion object can also have imaginary co-efficients

>>> q2=Quaternion(2,(3+2*I), x**2, 3.5*I)
>>> q2

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$2 + (3 + 2i)i + x2j + 3.5ik$

$2 + (3 + 2i)i + x2j + 3.5ik$

add()

四元数类中提供的此方法执行两个四元数对象的加法。

This method available in Quaternion class performs addition of two Quaternion objects.

>>> q1=Quaternion(1,2,3,4)
>>> q2=Quaternion(4,3,2,1)
>>> q1.add(q2)

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$5 + 5i + 5j + 5k$

$5 + 5i + 5j + 5k$

可以在四元数对象中添加数字或符号。

It is possible to add a number or symbol in a Quaternion object.

>>> q1+2

执行上面的代码片段后获得以下输出 −

The following output is obtained after executing the above code snippet −

$3 + 2i + 3j + 4k$

$3 + 2i + 3j + 4k$

>>> q1+x

执行上面的代码片段后获得以下输出 −

The following output is obtained after executing the above code snippet −

$(x + 1) + 2i + 3j + 4k$

$(x + 1) + 2i + 3j + 4k$

mul()

此方法执行两个四元数对象的乘法。

This method performs multiplication of two quaternion objects.

>>> q1=Quaternion(1,2,1,2)
>>> q2=Quaternion(2,4,3,1)
>>> q1.mul(q2)

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$(-11) + 3i + 11j + 7k$

$(-11) + 3i + 11j + 7k$

inverse()

此方法返回一个四元数对象的逆。

This method returns inverse of a quaternion object.

>>> q1.inverse()

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$\frac{1}{10} + (-\frac{1}{5})i + (-\frac{1}{10})j + (-\frac{1}{5})k$

$\frac{1}{10} + (-\frac{1}{5})i + (-\frac{1}{10})j + (-\frac{1}{5})k$

pow()

此方法返回一个四元数对象的幂。

This method returns power of a quaternion object.

>>> q1.pow(2)

执行上面的代码片段后获得以下输出 −

The following output is obtained after executing the above code snippet −

$(-8) + 4i + 2j + 4k$

$(-8) + 4i + 2j + 4k$

exp()

此方法计算一个四元数对象的指数,即eq

This method computes exponential of a Quaternion object i.e. eq

>>> q=Quaternion(1,2,4,3)
>>> q.exp()

执行上面的代码片段后获得以下输出 −

The following output is obtained after executing the above code snippet −

$e\cos(\sqrt29) + \frac{2\sqrt29e\sin(\sqrt29)}{29}i + \frac{4\sqrt29e\sin(\sqrt29)}{29}j + \frac{3\sqrt29e\sin}{29}k$

$e\cos(\sqrt29) + \frac{2\sqrt29e\sin(\sqrt29)}{29}i + \frac{4\sqrt29e\sin(\sqrt29)}{29}j + \frac{3\sqrt29e\sin}{29}k$

SymPy - Solvers

由于符号 = 和 == 在 Python 中被定义为赋值和相等运算符,它们无法用于制定符号方程式。SymPy 提供 Eq() 函数来设置方程式。

Since the symbols = and == are defined as assignment and equality operators in Python, they cannot be used to formulate symbolic equations. SymPy provides Eq() function to set up an equation.

>>> from sympy import *
>>> x,y=symbols('x y')
>>> Eq(x,y)

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

x = y

x = y

由于仅当 x-y=0 时,x=y 才成立,因此上述方程式可以写成 −

Since x=y is possible if and only if x-y=0, above equation can be written as −

>>> Eq(x-y,0)

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

x − y = 0

x − y = 0

SymPy 中的 solver 模块提供了 soveset() 函数,其原型如下 −

The solver module in SymPy provides soveset() function whose prototype is as follows −

solveset(equation, variable, domain)

默认的域是 S.Complexes。使用 solveset() 函数,我们可以如下求解代数方程式 −

The domain is by default S.Complexes. Using solveset() function, we can solve an algebraic equation as follows −

>>> solveset(Eq(x**2-9,0), x)

获得以下输出 −

The following output is obtained −

{−3, 3}

{−3, 3}

>>> solveset(Eq(x**2-3*x, -2),x)

执行上面的代码片段后获得以下输出 −

The following output is obtained after executing the above code snippet −

{1,2}

{1,2}

solveset 的输出是有限集的解。如果没有解,则返回空集

The output of solveset is a FiniteSet of the solutions. If there are no solutions, an EmptySet is returned

>>> solveset(exp(x),x)

执行上面的代码片段后获得以下输出 −

The following output is obtained after executing the above code snippet −

$\varnothing$

$\varnothing$

Linear equation

我们必须使用 linsolve() 函数来求解线性方程。

We have to use linsolve() function to solve linear equations.

举例来说,方程如下 −

For example, the equations are as follows −

x-y=4

x+y=1

>>> from sympy import *
>>> x,y=symbols('x y')
>>> linsolve([Eq(x-y,4),Eq( x + y ,1) ], (x, y))

执行上面的代码片段后获得以下输出 −

The following output is obtained after executing the above code snippet −

$\lbrace(\frac{5}{2},-\frac{3}{2})\rbrace$

$\lbrace(\frac{5}{2},-\frac{3}{2})\rbrace$

linsolve() 函数也可以解矩阵形式表示的线性方程。

The linsolve() function can also solve linear equations expressed in matrix form.

>>> a,b=symbols('a b')
>>> a=Matrix([[1,-1],[1,1]])
>>> b=Matrix([4,1])
>>> linsolve([a,b], (x,y))

如果执行以上代码片段,我们将得到以下输出 −

We get the following output if we execute the above code snippet −

$\lbrace(\frac{5}{2},-\frac{3}{2})\rbrace$

$\lbrace(\frac{5}{2},-\frac{3}{2})\rbrace$

Non-linear equation

为此,我们使用 nonlinsolve() 函数。此示例的方程 −

For this purpose, we use nonlinsolve() function. Equations for this example −

a2+a=0 a-b=0

>>> a,b=symbols('a b')
>>> nonlinsolve([a**2 + a, a - b], [a, b])

如果执行以上代码片段,我们将得到以下输出 −

We get the following output if we execute the above code snippet −

$\lbrace(-1, -1),(0,0)\rbrace$

$\lbrace(-1, -1),(0,0)\rbrace$

differential equation

首先,通过将 cls=Function 传递给 symbols 函数来创建一个未定义的函数。若要解微分方程,请使用 dsolve。

First, create an undefined function by passing cls=Function to the symbols function. To solve differential equations, use dsolve.

>>> x=Symbol('x')
>>> f=symbols('f', cls=Function)
>>> f(x)

执行上面的代码片段后获得以下输出 −

The following output is obtained after executing the above code snippet −

f(x)

f(x)

此处 f(x) 是一个未评估的函数。其导数如下 −

Here f(x) is an unevaluated function. Its derivative is as follows −

>>> f(x).diff(x)

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$\frac{d}{dx}f(x)$

$\frac{d}{dx}f(x)$

我们首先创建与以下微分方程对应的 Eq 对象

We first create Eq object corresponding to following differential equation

>>> eqn=Eq(f(x).diff(x)-f(x), sin(x))
>>> eqn

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$-f(x) + \frac{d}{dx}f(x)= \sin(x)$

$-f(x) + \frac{d}{dx}f(x)= \sin(x)$

>>> dsolve(eqn, f(x))

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$f(x)=(c1-\frac{e-xsin(x)}{2}-\frac{e-xcos(x)}{2})ex$

$f(x)=(c1-\frac{e-xsin(x)}{2}-\frac{e-xcos(x)}{2})ex$

SymPy - Plotting

SymPy 使用 Matplotlib 库作为后端来渲染数学函数的 2D 和 3D 图。确保在当前 Python 安装中可以使用 Matplotlib。如果没有,请使用以下命令安装相同的命令 -

SymPy uses Matplotlib library as a backend to render 2-D and 3-D plots of mathematical functions. Ensure that Matplotlib is available in current Python installation. If not, install the same using following command −

pip install matplotlib

绘图支持在 sympy.plotting 模块中定义。绘图模块中存在以下函数 -

Plotting support is defined in sympy.plotting module. Following functions are present in plotting module −

  1. plot − 2D line plots

  2. plot3d − 3D line plots

  3. plot_parametric − 2D parametric plots

  4. plot3d_parametric − 3D parametric plots

plot() 函数返回绘图类的一个实例。一个绘图图形可能有一个或多个 SymPy 表达式。虽然它能够使用 Matplotlib 作为后端,但也可以使用其他后端,如 texplot、pyglet 或 Google charts API。

The plot() function returns an instance of Plot class. A plot figure may have one or more SymPy expressions. Although it is capable of using Matplotlib as backend, other backends such as texplot, pyglet or Google charts API may also be used.

plot(expr, range, kwargs)

其中 expr 是任何有效的 symPy 表达式。如果没有注明,则范围使用默认值 (-10, 10)。

where expr is any valid symPy expression. If not mentioned, range uses default as (-10, 10).

以下示例绘制了 range(-10,10) 中每个值 x2 的值 -

Following example plots values of x2 for each value in range(-10,10) −

>>> from sympy.plotting import plot
>>> from sympy import *
>>> x=Symbol('x')
>>> plot(x**2, line_color='red')
range tuple

要为相同范围绘制多张图,请在范围元组之前给出多个表达式。

To draw multiple plots for same range, give multiple expressions prior to the range tuple.

>>> plot( sin(x),cos(x), (x, -pi, pi))
separate range

您还可以为每个表达式指定单独的范围。

You can also specify separate range for each expression.

plot((expr1, range1), (expr2, range2))

下图绘制了不同范围内的 sin(x) 和 cos(x)。

Following figure plots sin(x) and cos(x) over different ranges.

>>> plot( (sin(x),(x, -2*pi, 2*pi)),(cos(x), (x, -pi, pi)))
plot function

以下可选关键字参数可以在 plot() 函数中指定。

Following optional keyword arguments may be specified in plot() function.

  1. line_color − specifies color of the plot line.

  2. title − a string to be displayed as title

  3. xlabel − a string to be displayed as label for X axis

  4. ylabel − a string to be displayed as label for y axis

>>> plot( (sin(x),(x, -2*pi, 2*pi)),(cos(x), (x, -pi, pi)), line_color='red', title='SymPy plot example')
three dimensional plot

plot3d() 函数渲染一个三维图形。

The plot3d() function renders a three dimensional plot.

plot3d(expr, xrange, yrange, kwargs)

以下示例绘制一个三维曲面图形 −

Following example draws a 3D surface plot −

>>> from sympy.plotting import plot3d
>>> x,y=symbols('x y')
>>> plot3d(x*y, (x, -10,10), (y, -10,10))
2d plot

与 2D 图形类似,三维图形也可以有多个不同范围的图形。

As in 2D plot, a three dimensional plot can also have multiple plots each with different range.

>>> plot3d(x*y, x/y, (x, -5, 5), (y, -5, 5))
3 dimensional parametric line plot

plot3d_parametric_line() 函数渲染三维参数线图形。

The plot3d_parametric_line() function renders a 3 dimensional parametric line plot.

>>> from sympy.plotting import plot3d_parametric_line
>>> plot3d_parametric_line(cos(x), sin(x), x, (x, -5, 5))
parametric surface plot

要绘制参数曲面图形,请使用 plot3d_parametric_surface() 函数。

To draw a parametric surface plot, use plot3d_parametric_surface() function.

plot3d_parametric_surface(xexpr, yexpr, zexpr, rangex, rangey, kwargs)

>>> from sympy.plotting import plot3d_parametric_surface
>>> plot3d_parametric_surface(cos(x+y), sin(x-y), x-y, (x, -5, 5), (y, -5, 5))
plot 3d parametric surface function

SymPy - Entities

SymPy 中的几何模块允许创建二维实体,如线、圆等。然后我们可以获取有关它们的信息,例如检查共线或查找交点。

The geometry module in SymPy allows creation of two dimensional entities such as line, circle, etc. We can then obtain information about them such as checking colinearity or finding intersection.

Point

Point 类表示欧氏空间中的一个点。以下示例检查点的共线性:

Point class represents a point in Euclidean space. Following example checks for collinearity of points −

>>> from sympy.geometry import Point
>>> from sympy import *
>>> x=Point(0,0)
>>> y=Point(2,2)
>>> z=Point(4,4)
>>> Point.is_collinear(x,y,z)

Output

True

True

>>> a=Point(2,3)
>>> Point.is_collinear(x,y,a)

Output

False

False

Point 类的 distance() 方法计算两个点之间的距离

The distance() method of Point class calculates distance between two points

>>> x.distance(y)

Output

$2\sqrt2$

$2\sqrt2$

距离也可以用符号来表示。

The distance may also be represented in terms of symbols.

Line

线实体是由两个点对象获得的。intersection() 方法返回两条相交线段的交点。

Line entity is obtained from two Point objects. The intersection() method returns point of intersection if two lines intersect each other.

>>> from sympy.geometry import Point, Line
>>> p1, p2=Point(0,5), Point(5,0)
>>> l1=Line(p1,p2)
>>> l2=Line(Point(0,0), Point(5,5))
>>> l1.intersection(l2)

Output

[Point2D(5/2, 5/2)]

[Point2D(5/2, 5/2)]

>>> l1.intersection(Line(Point(0,0), Point(2,2)))

Output

[Point2D(5/2, 5/2)]

[Point2D(5/2, 5/2)]

>>> x,y=symbols('x y')
>>> p=Point(x,y)
>>> p.distance(Point(0,0))

Output

$\sqrt{x^2 + y^2}$

$\sqrt{x^2 + y^2}$

Triangle

这个函数用三个点对象构建一个三角形实体。

This function builds a triangle entity from three point objects.

Triangle(a,b,c)

Triangle(a,b,c)

>>> t=Triangle(Point(0,0),Point(0,5), Point(5,0))
>>> t.area

Output

$-\frac{25}{2}$

$-\frac{25}{2}$

Ellipse

一个椭圆几何实体是由一个对应于中心点的点对象和两个数字(分别代表水平和垂直半径)构成的。

An elliptical geometry entity is constructed by passing a Point object corresponding to center and two numbers each for horizontal and vertical radius.

ellipse(center, hradius, vradius)

ellipse(center, hradius, vradius)

>>> from sympy.geometry import Ellipse, Line
>>> e=Ellipse(Point(0,0),8,3)
>>> e.area

Output

$24\pi$

$24\pi$

可以使用偏心参数间接给出垂直半径。

The vradius can be indirectly provided by using eccentricity parameter.

>>> e1=Ellipse(Point(2,2), hradius=5, eccentricity=Rational(3,4))
>>> e1.vradius

Output

$\frac{5\sqrt7}{4}$

$\frac{5\sqrt7}{4}$

椭圆的 apoapsis 是焦点与轮廓线之间的最长距离。

The apoapsis of the ellipse is the greatest distance between the focus and the contour.

>>> e1.apoapsis

Output

$\frac{35}{4}$

$\frac{35}{4}$

下述语句计算椭圆的圆周率 -

Following statement calculates circumference of ellipse −

>>> e1.circumference

Output

$20E(\frac{9}{16})$

$20E(\frac{9}{16})$

椭圆的 equation 方法返回椭圆的方程。

The equation method of ellipse returns equation of ellipse.

>>> e1.equation(x,y)

Output

$(\frac{x}{5}-\frac{2}{5})^2 + \frac{16(y-2)2}{175} - 1$

$(\frac{x}{5}-\frac{2}{5})^2 + \frac{16(y-2)2}{175} - 1$

SymPy - Sets

在数学中,一个集合是有序离散对象 مجموعة منظمة من كائنات منفصلة مرتبة جيدًا 的集合,这些对象可能是数字、人、字母或甚至是其他集合。集合也是 Python 中的内置类型之一。SymPy 提供集合模块。它包含不同类型的集合的定义,并具有执行交集、并集等集合运算的功能。

In mathematics, a set is a well-defined collection of distinct objects which may be numbers, people, letters of the alphabet, or even other sets. Set is also one of the built-in types in Python. SymPy provides sets module. It contains definitions of different types of set and has functionality to perform set operations such as intersection, union, etc.

集合是 SymPy 中其他任何类型的集合的基本类。请注意,它与 Python 的内置集合数据类型不同。区间类别表示实区间,其边界属性返回一个 FiniteSet 对象。

Set is a base class for any other type of set in SymPy. Note that it is different from built-in set data type of Python. Interval class represents real intervals and its boundary property returns a FiniteSet object.

>>> from sympy import Interval
>>> s=Interval(1,10).boundary
>>> type(s)

sympy.sets.sets.FiniteSet

sympy.sets.sets.FiniteSet

有限集合是离散数字的集合。它可以从列表或字符串等任何序列对象中获取。

FiniteSet is a collection of discrete numbers. It can be obtained from any sequence object such as list or string.

>>> from sympy import FiniteSet
>>> FiniteSet(range(5))

Output

$\lbrace\lbrace0,1,…​,4\rbrace\rbrace$

$\lbrace\lbrace0,1,…​,4\rbrace\rbrace$

>>> numbers=[1,3,5,2,8]
>>> FiniteSet(*numbers)

Output

$\lbrace1,2,3,5,8\rbrace$

$\lbrace1,2,3,5,8\rbrace$

>>> s="HelloWorld"
>>> FiniteSet(*s)

Output

{H,W,d,e,l,o,r}

{H,W,d,e,l,o,r}

请注意,在内置集合中,SymPy 的集合也是离散对象的集合。

Note that, as in built-in set, SymPy’s Set is also a collection of distinct objects.

ConditionSet 是满足给定条件的元素的集合

ConditionSet is a set of elements that satisfy a given condition

>>> from sympy import ConditionSet, Eq, Symbol
>>> x=Symbol('x')
>>> s=ConditionSet(x, Eq(x**2-2*x,0), Interval(1,10)) >>> s

Output

$\lbrace x\mid x\in[1,10]∧x^2 - 2x =0\rbrace$

$\lbrace x\mid x\in[1,10]∧x^2 - 2x =0\rbrace$

Union 是一个复合集。它包含两个集合中的所有元素。请注意,同时出现在这两个集合中的元素只在并集当中出现一次。

Union is a compound set. It includes all elements in two sets. Note that elements that are found in both, will appear only once in the Union.

>>> from sympy import Union
>>> l1=[3,1,5,7]
>>> l2=[9,7,2,1]
>>> a=FiniteSet(*l1)
>>> b=FiniteSet(*l2)
>>> Union(a,b)

Intersection 相反,只包含同时出现在两个集合中的那些元素。

Intersection on the other hand contains only those elements that are present in both.

>>> from sympy import Intersection
>>> Intersection(a,b)

ProductSet 对象表示两个集合中元素的笛卡尔积。

ProductSet object represents Cartesian product of elements in both sets.

>>> from sympy import ProductSet
>>> l1=[1,2]
>>> l2=[2,3]
>>> a=FiniteSet(*l1)
>>> b=FiniteSet(*l2)
>>> set(ProductSet(a,b))

Complement(a,b) 保留了集合 a 中的元素,排除了 b 集合中存在的元素。

Complement(a,b) retains elements in a excluding elements that are common with b set.

>>> from sympy import Complement
>>> l1=[3,1,5,7]
>>> l2=[9,7,2,1]
>>> a=FiniteSet(*l1)
>>> b=FiniteSet(*l2)
>>> Complement(a,b), Complement(b,a)

SymmetricDifference 集合只包含两个集合中不常见的元素。

SymmetricDifference set contains only uncommon elements in both sets.

>>> from sympy import SymmetricDifference
>>> l1=[3,1,5,7]
>>> l2=[9,7,2,1]
>>> a=FiniteSet(*l1)
>>> b=FiniteSet(*l2)
>>> SymmetricDifference(a,b)

Output

{2,3,5,9}

{2,3,5,9}

SymPy - Printing

SymPy 中提供有若干打印机。以下是部分列表 -

There are several printers available in SymPy. Following is a partial list −

  1. str

  2. srepr

  3. ASCII pretty printer

  4. Unicode pretty printer

  5. LaTeX

  6. MathML

  7. Dot

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

SymPy objects can also be sent as output to code of various languages, such as C, Fortran, Javascript, Theano, and Python.

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

SymPy uses Unicode characters to render output in form of pretty print. If you are using Python console for executing SymPy session, the best pretty printing environment is activated by calling init_session() function.

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

适用于 SymPy 1.5.1 的 IPython 控制台(Python 3.7.4-64 位)(基本类型:python)。

IPython console for SymPy 1.5.1 (Python 3.7.4-64-bit) (ground types: python).

已执行以下命令 -

These commands were executed −

>>> 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/. 找到文档

Documentation can be found at https://docs.sympy.org/1.5.1/.

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

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

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

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

If LATEX is not installed, but Matplotlib is installed, it will use the Matplotlib rendering engine. If Matplotlib is not installed, it uses the Unicode pretty printer. However, Jupyter notebook uses MathJax to render LATEX.

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

In a terminal that does not support Unicode, ASCII pretty printer is used.

ascii pretty printer

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

To use ASCII printer use pprint() function with use_unicode property set to False

>>> pprint(Integral(sqrt(1/x),x),use_unicode=False)
unicode pretty printer

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

The Unicode pretty printer is also accessed from pprint() and pretty(). If the terminal supports Unicode, it is used automatically. If pprint() is not able to detect that the terminal supports unicode, you can pass use_unicode=True to force it to use Unicode.

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

To get the LATEX form of an expression, use latex() function.

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

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

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

你还可以使用 mathml 打印机。为此,导入 print_mathml 函数。可以通过 mathml() 函数获取字符串版本。

You can also use mathml printer. for that purpose, import print_mathml function. A string version is obtained by mathml() function.

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

<apply>

<apply>

<int/>

<int/>

<bvar>

<bvar>

<ci>x</ci>

<ci>x</ci>

</bvar>

</bvar>

<apply>

<apply>

<root/>

<root/>

<apply>

<apply>

<power/>

<power/>

<ci>x</ci>

<ci>x</ci>

<cn>-1</cn>

<cn>-1</cn>

</apply>

</apply>

</apply>

</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>'

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