《Python数据分析技术栈》第03章 02 使用Sympy解决数学问题(Using Sympy for math problems)

02 使用Sympy解决数学问题(Using Sympy for math problems)

《Python数据分析技术栈》第03章 02 使用Sympy解决数学问题(Using Sympy for math problems)

SymPy is a library in Python that can be used for solving a wide range of mathematical problems. We initially look at how SymPy functions can be used in algebra - for solving equations and factorizing expressions. After this, we cover a few applications in set theory and calculus.

SymPy 是 Python 中的一个库,可用于解决各种数学问题。我们首先来看看 SymPy 函数如何用于代数–解方程和因式分解表达式。之后,我们将介绍集合论和微积分中的一些应用。

The SymPy module can be imported using the following statement.

可以使用以下语句导入 SymPy 模块。

import sympy

If you have not already installed the sympy module, go to the Anaconda Prompt and enter the following command:

如果尚未安装 sympy 模块,请转到 Anaconda 提示符并输入以下命令:

pip install sympy

Let us now use this module for various mathematical problems, beginning with the factorization of expressions.

现在,让我们用这个模块来解决各种数学问题,首先是表达式的因式分解。

代数表达式的因式分解(Factorization of an algebraic expression)

Factorization of expressions involves splitting them into simpler expressions or factors. Multiplying these factors gives us the original expression.

表达式的因式分解是指将表达式拆分成更简单的表达式或因式。将这些因式相乘,就得到了原来的表达式。

As an example, an algebraic expression, like x^2 − y^2, can be factorized as: (x-y)*(x+y).

例如,一个代数表达式,如 x^2 - y^2,可以因式分解为 (x-y)*(x+y).

SymPy provides us functions for factorizing expressions as well as expanding expressions.

SymPy 提供了对表达式进行因式分解和展开的函数。

An algebraic expression contains variables which are represented as “symbols” in SymPy. Before SymPy functions can be applied, a variable in Python must be converted into a symbol object, which is created using the symbols class (for defining multiple symbols) or the Symbol class (for defining a single symbol). We then import the factor and expand functions, and then pass the expression we need to factorize or expand as arguments to these functions, as shown in the following.

代数表达式包含变量,这些变量在 SymPy 中表示为 “符号”。在应用 SymPy 函数之前,必须将 Python 中的变量转换为符号对象,符号对象是使用 symbols 类(用于定义多个符号)或 Symbol 类(用于定义单个符号)创建的。然后,我们导入 factor 和 expand 函数,并将需要因式分解或展开的表达式作为参数传递给这些函数,如下所示。

# importing the symbol classes
from sympy import symbols, Symbol

# importing the functions
from sympy import factor, expand

# defining the symbol objects
x, y = symbols('x,y')
a = Symbol('a')

# factorizing an expression
factorized_expr = factor(x ** 2 - y ** 2)

# expanding an expression
expanded_expr = expand((x - y) ** 3)
print("After factorizing x**2-y**2:", factorized_expr)
print("After expanding (x-y)**3:", expanded_expr)

解代数方程(单变量)(Solving algebraic equations (for one variable))

An algebraic equation contains an expression, with a series of terms, equated to zero. Let us now solve the equation x2 − 5x + 6 = 0, using the solve function in SymPy.

代数方程包含一个表达式,其中的一系列项都等于零。现在,让我们使用 SymPy 中的求解函数解方程 x2 - 5x + 6 = 0。

We import the solve function from the SymPy library and pass the equation we want to solve as an argument to this function, as shown in the following. The dict parameter produces the output in a structured format, but including this parameter is optional.

我们从 SymPy 库中导入求解函数,并将想要求解的方程作为参数传递给该函数,如下所示。dict 参数将以结构化格式生成输出,但包含该参数是可选的。

# importing the solve function
from sympy import solve

exp = "x**2-5*x+6"

# using the solve function to solve an equation
print(solve(exp, dict=True))

解同步方程(两个变量)(Solving simultaneous equations (for two variables))

The solve function can also be used to solve two equations simultaneously, as shown in the following code block.

求解函数还可用于同时求解两个方程,如以下代码块所示。

from sympy import symbols, solve

x, y = symbols('x,y')
exp1 = 2 * x - y + 4
exp2 = 3 * x + 2 * y - 1
print(solve((exp1, exp2), dict=True))

求解用户输入的表达式(Solving expressions entered by the user)

Instead of defining the expressions, we can have the user enter expressions using the input function. The issue is that the input entered by the user is treated as a string, and SymPy functions are unable to process such an input.

The sympify function can be used to convert any expression to a type that is compatible with SymPy. Note that the user must enter mathematical operators like *, **, and so on when the input is entered. For example, if the expression is 2*x+3, the user cannot skip the asterisk symbol while entering the input. If the user enters the input as 2x+3, an error would be produced. A code example has been provided in the following code block to demonstrate the sympify function.

sympify 函数可用于将任何表达式转换为与 SymPy 兼容的类型。请注意,用户在输入时必须输入***等数学运算符。例如,如果表达式为 2*x+3,用户在输入时不能跳过星号。如果用户输入 2x+3,就会出错。下面的代码块提供了一个代码示例来演示 sympify 函数。

from sympy import sympify, solve

expn = input("Input an expression:")  # x**2-9
symp_expn = sympify(expn)
print(solve(symp_expn, dict=True))

用图形解同步方程(Solving simultaneous equations graphically)

Algebraic equations can also be solved graphically. If the equations are plotted on a graph, the point of intersection of the two lines represents the solution.

代数方程也可以用图形来解。如果将方程绘制在图形上,两条直线的交点就代表解。

The plot function from the sympy.plotting module can be used to plot the equations, with the two expressions being passed as arguments to this function.

可以使用 sympy.plotting 模块中的 plot 函数绘制方程,并将两个表达式作为参数传递给该函数。

from sympy import symbols, solve
from sympy.plotting import plot
%matplotlib inline

x, y = symbols('x,y')
plot(x+4,3*x)
solve((x+4-y,3*x-y),dict=True)

创建和操作集合(Creating and manipulating sets)

A set is a collection of unique elements, and there is a multitude of operations that can be operations that can be applied on sets. Sets are represented using Venn diagrams, which depict the relationship between two or more sets.

集合是唯一元素的集合,可以对集合进行多种运算。集合用维恩图表示,维恩图描述了两个或多个集合之间的关系。

SymPy provides us with functions to create and manipulate sets.

SymPy 为我们提供了创建和操作集合的函数。

First, you need to import the FiniteSet class from the SymPy package, to work with sets.

首先,你需要从 SymPy 软件包中导入 FiniteSet 类,以便处理集合。

from sympy import FiniteSet

Now, declare an object of this class to create a set and initialize it using the numbers you want in your set.

现在,声明该类的一个对象以创建一个集合,并使用集合中的数字对其进行初始化。

s=FiniteSet(1,2,3)

We can also create a set from a list, as shown in the following statement.

我们还可以从列表中创建集合,如下语句所示。

l=[1,2,3]
s=FiniteSet(*l)

集合的并集和交集(Union and intersection of sets)

The union of two sets is the list of all distinct elements in both the sets while the intersection of two sets includes the elements common to the two sets.

两个集合的联集是两个集合中所有不同元素的列表,而两个集合的交集则包括两个集合的共同元素。

SymPy provides us a means to calculate the union and intersection of two sets using the union and intersect functions.

SymPy 提供了使用 union 和 intersect 函数计算两个集合的并集和交集的方法。

We use the FiniteSet class to create sets, and then apply the union and intersect functions on them, as demonstrated below.

我们使用 FiniteSet 类创建集合,然后在集合上应用 union 和 intersect 函数,如下所示。

from sympy import FiniteSet

s1 = FiniteSet(1, 2, 3)
s2 = FiniteSet(2, 3, 4)
union_set = s1.union(s2)
intersect_set = s1.intersect(s2)
print("Union of the sets is:", union_set)
print("Intersection of the sets is:", intersect_set)

查找事件发生的概率(Finding the probability of an event)

The probability of an event is the likelihood of the occurrence of an event, defined numerically.

事件概率是指事件发生的可能性,以数字形式定义。

Using sets to define our events and sample space, we can solve questions in probability with the help of SymPy functions.

利用集合来定义事件和样本空间,我们可以借助 SymPy 函数来解决概率问题。

Let us consider a simple example, where we find the probability of finding a multiple of 3 among the first ten natural numbers.

让我们举一个简单的例子,计算在前十个自然数中找到 3 的倍数的概率。

To answer this, we first define our sample space, “s”, as a set with numbers from 1 to 10. Then, we define the event, denoted by the letter ‘a’, which is the occurrence of a multiple of 3. We then find the probability of this event (‘a’) by defining the number of elements in this event by the number of elements in the sample space using the len function. This is demonstrated in the following.

要回答这个问题,我们首先要把样本空间 "s "定义为一个从 1 到 10 的数字集合。然后,我们用字母 "a "定义一个事件,即出现 3 的倍数的事件。下面将对此进行演示。

from sympy import FiniteSet

s = FiniteSet(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
a = FiniteSet(3, 6, 9)
p = len(a) / len(s)

print(p)

解决微积分问题(Solving questions in calculus)

We will learn how to use SymPy to calculate the limiting value, derivate, and the definite and indefinite integral of a function.

我们将学习如何使用 SymPy 计算函数的极限值、导数、定积分和不定积分。

函数的极限(Limit of a function)

The limiting value of the function, f(x), is the value of the function as x approaches a particular value.

函数的极限值 f(x) 是指当 x 接近某一特定值时的函数值。

For example, if we take the function 1/x, we see that as x increases, the value of 1/x goes on reducing. As x approaches an infinitely large value, 1/x becomes closer to 0. The limiting value is calculated using the SymPy function - limit, as shown below.

例如,如果我们取函数 1/x,我们会发现随着 x 的增大,1/x 的值会不断减小。当 x 接近一个无限大的值时,1/x 会越来越接近 0。

from sympy import limit, Symbol

x = Symbol('x')

print(limit(1 / x, x, 0)) # ∞

函数的导数(Derivative of a function)

The derivative of a function defines the rate of change of this function with respect to an independent variable. If we take distance as the function and time as the independent variable, the derivate of this function is the rate of change of this function with respect to time, which is speed.

函数的导数定义了该函数相对于自变量的变化率。如果我们把距离作为函数,时间作为自变量,那么这个函数的导数就是这个函数相对于时间的变化率,也就是速度。

SymPy has a function, diff, which takes the expression (whose derivative is to be calculated) and the independent variable as arguments, and returns the derivative of the expression.

SymPy 有一个函数 diff,它将表达式(需要计算其导数)和自变量作为参数,并返回表达式的导数。

from sympy import Symbol, diff

x = Symbol('x')

# defining the expression to be differentiated
expr = x ** 2 - 4

# applying the diff function to this expression
d = diff(expr, x)

print(d)

函数积分(Integral of a function)

The integral of a function is also called an anti-derivate. The definite integral of a function for two points, say “p” and “q”, is the area under the curve between limits. For an indefinite integral, these limits are not defined.

函数的积分也称为反积分。一个函数对两点(例如 "p "和 “q”)的定积分是两极限之间的曲线下面积。对于不定积分来说,这些极限是不确定的。

In SymPy, the integral can be calculated using the integrate function.

在 SymPy 中,可以使用 integrate 函数计算积分。

Let us calculate the indefinite integral of the differential (2x) of the function we saw in the last example.

让我们计算上一个例子中函数的微分 (2x) 的不定积分。

from sympy import Symbol, diff
from sympy import integrate

x = Symbol('x')

# defining the expression to be differentiated
expr = x ** 2 - 4

# applying the diff function to this expression
d = diff(expr, x)

print(d)

# applying the integrate function
print(integrate(d, x))

Let us calculate the definite integral of the above output, using the integrate function. The arguments accepted by the integrate function include the limits, 1 and 4 (as a tuple), along with the variable (symbol), “x”

让我们使用 integrate 函数计算上述输出的定积分。积分函数接受的参数包括限值 1 和 4(作为一个元组),以及变量(符号)“x”。

from sympy import Symbol, diff
from sympy import integrate

x = Symbol('x')

# defining the expression to be differentiated
expr = x ** 2 - 4

# applying the diff function to this expression
d = diff(expr, x)

print(d)
print(integrate(d, (x, 1, 4)))

你可能感兴趣的:(Python数据分析技术栈,python,数据分析,python,数据分析,开发语言)