Introduction to Sympy algebraic symbolic operations in Python

不言
Release: 2019-03-29 11:04:38
forward
6996 people have browsed it

This article brings you an introduction to Sympy algebraic symbolic operations in Python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

In our nearly 10 years of study in junior high school, high school and college, mathematics has always played a very large role. However, looking back on the past, we can find that we spent a lot of time solving problems repeatedly and doing calculations. On the Internet, calculation methods, calculation skills, written calculation skills and the memory of mathematical formulas seem to have become everything we learn mathematics. These memories and skills are forgotten within a few years, but many people still remember the shadow; written calculations and problem solving were replaced by software in AI, graphics, data analysis, etc. So what is left of the mathematics of our student days?

Calculators and Mathematics

Speaking of mathematical calculators, the four most common operations we see are addition, subtraction, multiplication and division. With it, we can get rid of the traditional calculations of written calculations and mental calculations. pain. Addition, subtraction, multiplication and division of more than four digits are actually not difficult in terms of mathematical principles. However, if we do not rely on a calculator and rely only on our calculation ability (written arithmetic and mental arithmetic), not only will the accuracy of the calculation be greatly reduced, but it will also make the calculation more difficult. Our use of mathematics remains at a very shallow level.

Although the four arithmetic operations are so simple, the mental arithmetic of multi-digit operations is classified as a genius-like ability in our lives. However, the application of mathematics should be practical and popularized, rather than just a patent for geniuses. The calculator has changed everything. This is the charm of the calculator.
The calculator can also perform scientific operations, such as exponentiation, square root, exponent, logarithm, trigonometric functions, etc. Although this knowledge can also be calculated with pen and paper in our junior high school days, it is limited to some extreme Once common and simple operations become complicated, it becomes a complicated project to perform operations with pen and paper. Therefore, calculators can bring us closer to the application of mathematics.

But the mathematics we learned in our student days is far more than these, especially advanced mathematics (calculus), linear algebra, probability and statistics and other mathematical knowledge are widely used (I only learned about it later), but because of their The calculations are very complex. Even if we master this knowledge, it is not easy to apply it. Are there any calculators for calculus, linear algebra, probability and statistics, etc.?

The answer is yes. They are the Computer Algebra System, or CAS for short. Python's Sympy library also supports calculus, linear algebra, etc. with mathematical symbols for operations.

With a calculator, we can truly break away from the complex mathematical problem-solving itself and spend our energy on learning mathematical principles and applications, and this is the meaning of mathematical learning (at work).

Computer Algebra System

Sympy can implement operations on mathematical symbols, use it to perform symbolic derivation and verification of mathematical expressions, and process derivatives, limits, calculus, and equations with mathematical symbols. Groups, matrices, etc., are as simple as a scientific calculator, similar to Computer Algebra System CAS. Although CAS is usually a visualization software, Wikipedia also classifies Sympy as CAS.

Several well-known mathematical software such as Mathematica, Maxima, Matlab (requires Symbolic Math Toolbox), Maple etc. can perform symbolic operations. In the previous article, we have compared Python with R and Matlab. Obviously, Python has very obvious advantages in specified scenarios, so I investigated the comparison between Sympy and Mathematica. When entering formulas and Sympy is really not good at generating charts (Python has other libraries to make up for this). Sympy can basically do anything Mathematica can do.

So in the field of professional mathematics (mathematics, data science, etc.), Python has formed an extremely complete ecological chain because it has many and powerful third-party libraries, even in the face of the most powerful force in the world. The most hard-core software is also true.

The next issue of this column on learning mathematics with Python will also introduce some very practical mathematical tools and mathematics teaching resources to make learning mathematics easier and more vivid.

Sympy’s symbolic operations

If you studied mathematics before and learned about the computer algebra system CAS, you will be familiar with the operations of mathematical symbols. However, if you were a programmer before, you may be a little unfamiliar. It’s so clear, let’s find out next.

The difference between Sympy and Math functions

Let’s first take a look at the difference between the Sympy library and Python’s built-in Math function in processing numerical calculations. In order to make the code executable, the following code is based on the complete code of Python3.

import sympy,math
print(math.sqrt(8))
print(sympy.sqrt(8))
Copy after login

After execution, the result is displayed as:

2.8284271247461903
2*sqrt(2)
Copy after login

The math module directly solves a floating point value, while Sympy uses mathematical symbols to express the result. Combined with LaTex syntax, you can get Take the one we are most familiar with in textbooks: $2\sqrt{2}$.

Mathematical symbols and expressions

我们要对数学方程组、微积分等进行运算时,就会遇到变量比如x,y,z,f等的问题,也会遇到求导、积分等代数符号表达式,而Sympy就可以保留变量,计算有代数符号的表达式的。

from sympy import *
x = Symbol('x')
y = Symbol('y')
k, m, n = symbols('k m n')
print(3*x+y**3)
Copy after login

输出的结果为:3*x + y**3,转化为LaTex表示法之后结果为$3x+y^3$,输出的结果就带有x和y变量。Symbol()函数定义单个数学符号;symbols()函数定义多个数学符号。

折叠与展开表达式

factor()函数可以折叠表达式,而expand()函数可以展开表达式,比如表达式:$x^4+xy+8x$,折叠之后应该是$x(x^3+y+8)$。我们来看具体的代码:

from sympy import *
x,y = symbols('x y')
expr=x**4+x*y+8*x
f_expr=factor(expr)
e_expr=expand(f_expr)
print(f_expr)
print(e_expr)
Copy after login

表达式的折叠与展开,对应的数学知识就是因式分解,相关的数学知识在人教版初二的教程里。用Python学习数学专栏的目的就是要Python与初高中、大学的数学学习结合起来,让数学变得更加简单生动。

表达式化简

simplify()函数可以对表达式进行化简。有一些表达式看起来会比较复杂,就拿人教版初二上的一道多项式的乘法为例,简化$(2x)^3(-5xy^2)$。

from sympy import *
x,y = symbols('x y')
expr=(2*x)**3*(-5*x*y**2)
s_expr=simplify(expr)
print(s_expr)
Copy after login

求解方程组

在人教版的数学教材里,我们初一上会接触一元一次方程组,初一下就会接触二元一次方程、三元一次方程组,在初三上会接触到一元二次方程,使用Sympy的solve()函数就能轻松解题。

解一元一次方程

我们来求解这个一元一次方程组。(题目来源于人教版七年级数学上)
$$6 \times x + 6 \times(x-2000)=150000$$

from sympy import *
x = Symbol('x')
print(solve(6*x + 6*(x-2000)-150000,x))
Copy after login

我们需要掌握Python的代码符号和数学符号之间的对应关系,解一元一次方程就非常简单。

解二元一次方程组

我们来看如何求解二元一次方程组。(题目来自人教版七年级数学下)

$$ \begin{cases} x+ y =10,\\ 2 \times x+ y=16   \end{cases} $$

from sympy import *
x,y = symbols('x y')
print(solve([x + y-10,2*x+y-16],[x,y]))
Copy after login

很快就可以得出{x: 6, y: 4},也就是
$$x=6,y=4$$。

解三元一次方程组

我们来看如何解三元一次方程组。(题目来自人教版七年级数学下)

$$ \begin{cases} x+y+z=12,\\ x+2y+5z=22,\\ x=4y.   \end{cases} $$

执行之后,很快可以得出结果{x: 8, y: 2, z: 2},也就是
$$x=8,y=2,z=2$$

解一元二次方程组

比如我们来求解人教版九年级一元二次方程组比较经典的一个题目,$ax^2+bx+c=0$.

from sympy import *
x,y = symbols('x y')
a,b,c=symbols('a b c')
expr=a*x**2 + b*x + c
s_expr=solve( expr, x)
print(s_expr)
Copy after login

执行之后得出的结果为[(-b + sqrt(-4*a*c + b**2))/(2*a), -(b + sqrt(-4*a*c + b**2))/(2*a)],我们知道根与系数的关系二次方程会有两个解,这里的格式就是一个列表。转为我们常见的数学公式即为:
$$\frac{-b+\sqrt{-4ac+b^2}}{2a} 、-\frac{b+\sqrt{-4ac+b^2}}{2a}$$

微积分Calculus

微积分是大学高等数学里非常重要的学习内容,比如求极限、导数、微分、不定积分、定积分等都是可以使用Sympy来运算的。
求极限
Sympy是使用limit(表达式,变量,极限值)函数来求极限的,比如我们要求$\lim \limits_{x \to 0} \frac{sinx(x)}{x}$的值。

from sympy import *
x, y, z = symbols('x y z')
expr = sin(x)/x
l_expr=limit(expr, x, 0)
print(l_expr)
Copy after login

执行后即可得到结果为1。

求导

可以使用diff(表达式,变量,求导的次数)函数对表达式求导,比如我们要对$sin(x)e^x$进行$x$求导,以及求导两次,代码如下:

from sympy import *
x,y = symbols('x y')
expr=sin(x)*exp(x)
diff_expr=diff(expr, x)
diff_expr2=diff(expr,x,2)
print(diff_expr)
print(diff_expr2)
Copy after login

求导一次的结果就是exp(x)*sin(x) + exp(x)*cos(x),也就是$e^xsin(x)+e^xcos(x)$;求导两次的结果是2*exp(x)*cos(x),也就是
$$2e^xcosx$$

求不定积分

Sympy是使用integrate(表达式,变量)来求不定积分的,比如我们要求$\int(e^x\sin{(x)} + e^x\cos{(x)})\,dx$

from sympy import *
x,y = symbols('x y')
expr=exp(x)*sin(x) + exp(x)*cos(x)
i_expr=integrate(expr,x)
print(i_expr)
Copy after login

执行之后的结果为:exp(x)*sin(x) 转化之后为:
$$e^xsin(x)$$

求定积分

Sympy同样是使用integrate()函数来做定积分的求解,只是语法不同:integrate(表达式,(变量,下区间,上区间)),我们来看如果求解
$\int_{-\infty}^\infty \sin{(x^2)}\,dx$

from sympy import *
x,y = symbols('x y')
expr=sin(x**2)
i_expr=integrate(expr, (x, -oo, oo))
print(i_expr)
Copy after login

执行之后的结果为sqrt(2)*sqrt(pi)/2,也就是
$$\frac{\sqrt{2}\sqrt{\pi}}{2}$$

Sympy能够做的也远不止这些,初高中、大学的数学运算题在Sympy极为丰富的功能里不过只是开胃入门小菜而已。

本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注PHP中文网的python视频教程栏目!

The above is the detailed content of Introduction to Sympy algebraic symbolic operations in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template