📜  Python - 求解多变量的线性方程

📅  最后修改于: 2022-05-13 01:54:20.212000             🧑  作者: Mango

Python - 求解多变量的线性方程

先决条件: Sympy.solve()

在本文中,我们将讨论如何求解具有多个变量的线性方程。例如,假设方程中有两个变量。方程式如下:

当我们解这个方程时,我们得到 x=1, y=0 作为解之一。在Python中,我们使用 Eq() 方法从表达式创建一个方程。

例如,如果我们有表达式 x+y = 1。它可以写成 Eq(x+y,1)

求解具有两个变量的方程

使用 Eq() 方法构造方程。要求解方程,请将它们作为参数传递给solve()函数。

例子 :

Python3
# importing library sympy
from sympy import symbols, Eq, solve
  
# defining symbols used in equations
# or unknown variables
x, y = symbols('x,y')
  
# defining equations
eq1 = Eq((x+y), 1)
print("Equation 1:")
print(eq1)
eq2 = Eq((x-y), 1)
print("Equation 2")
print(eq2)
  
# solving the equation
print("Values of 2 unknown variable are as follows:")
  
print(solve((eq1, eq2), (x, y)))


Python3
# importing library sympy
from sympy import symbols, Eq, solve
  
# defining symbols used in equations
# or unknown variables
x, y, z = symbols('x,y,z')
  
# defining equations
eq1 = Eq((x+y+z), 1)
print("Equation 1:")
print(eq1)
  
eq2 = Eq((x-y+2*z), 1)
print("Equation 2")
print(eq2)
  
eq3 = Eq((2*x-y+2*z), 1)
print("Equation 3")
  
# solving the equation and printing the 
# value of unknown variables
print("Values of 3 unknown variable are as follows:")
print(solve((eq1, eq2, eq3), (x, y, z)))


输出:

Equation 1:
Eq(x + y, 1)
Equation 2
Eq(x - y, 1)
Values of 2 unknown variable are as follows:
{x: 1, y: 0} 

求解具有三个变量的方程

使用 Eq() 构造以下方程,然后求解以找到未知变量。

例子:

蟒蛇3

# importing library sympy
from sympy import symbols, Eq, solve
  
# defining symbols used in equations
# or unknown variables
x, y, z = symbols('x,y,z')
  
# defining equations
eq1 = Eq((x+y+z), 1)
print("Equation 1:")
print(eq1)
  
eq2 = Eq((x-y+2*z), 1)
print("Equation 2")
print(eq2)
  
eq3 = Eq((2*x-y+2*z), 1)
print("Equation 3")
  
# solving the equation and printing the 
# value of unknown variables
print("Values of 3 unknown variable are as follows:")
print(solve((eq1, eq2, eq3), (x, y, z)))

输出:

Equation 1:
Eq(x + y + z, 1)
Equation 2
Eq(x - y + 2*z, 1)
Equation 3
Values of 3 unknown variable are as follows:
{x: 0, y: 1/3, z: 2/3}