Use the sympy library to solve equations in Python

1 Introduction to the sympy library

The sympy library is a symbolic mathematical computing system based on the Python language. It is characterized by using symbols instead of numbers to deal with mathematical problems.

2 Symbolic variables

The sympy library handles mathematical problems through symbols, so when using the sympy library, it is necessary to define symbols to represent unknowns. This defined symbol is called a symbol variable. Mathematical expressions can then be represented by this symbolic variable. Use the symbols() function in the sympy library to define symbol variables, the code is as follows.

from sympy import *
x = symbols('x')

Among them, the variable x is a symbol variable, representing the symbol 'x'. You can also define multiple symbol variables through the symbols() function, the code is as follows.

x, y, z = symbols('x, y, z')

3 Solving equations

Once the symbolic variables are defined, equations can be represented by symbolic variables.

3.1 Solving linear equations in one variable

The unary linear equation "2x-3=5" can be expressed as "2*x-3-5" with symbolic variables, and then solve the equation through the solve() function of sympy, the code is as follows.

>>> ex = 2*x-3-5
>>> solve(ex, x)
[4]

The first parameter of the solve() function represents the equation represented by the symbolic variable, the second parameter specifies the symbolic variable, and the result obtained is a list, and the elements in the list are the solutions of the equation.

3.2 Solving quadratic equations in one variable

For the binary linear equation "x2-2x+3=2", the solution code is as follows:

>>> ex = x**2-2*x+3-2
>>> solve(ex, x)
[1]

The solution to this linear equation in two variables is 1.

3.3 Solving the system of equations

For the system of equations "2x-y=3 3x+y=7", use the following code to solve it.

>>> x, y = symbols('x, y')
>>> ex1 = 2*x-y-3
>>> ex2 = 3*x+y-7
>>> solve([ex1, ex2], [x, y])
{x: 2, y: 1}

Among them, for solving a system of equations, the first parameter of the solve() function is set as a list, and each element in the list represents each equation in the system of equations; the second parameter is also set as a list, and the elements in the list Each element represents an unknown of the system of equations.

It should be noted that if the sympy library is not installed, it needs to be installed through the pip install sympy command in the console.

Guess you like

Origin blog.csdn.net/hou09tian/article/details/131966374