Python求解三元一次方程
时间: 2024-01-05 22:20:27 浏览: 141
python简单的三元一次方程求解实例
以下是一个用Python求解三元一次方程的例子:
```python
import sympy as sp
# 输入三元一次方程
equations = []
for i in range(3):
equation = input("请输入第%d个三元一次方程:" % (i + 1))
equations.append(equation)
# 提取方程中的系数和常数项
coefficients = []
constants = []
for equation in equations:
equation_parts = equation.split("=")
equation_left = equation_parts[0].strip()
equation_right = equation_parts[1].strip()
equation_left_terms = equation_left.split("+")
equation_right_terms = equation_right.split("+")
equation_terms = equation_left_terms + equation_right_terms
equation_coefficients = []
equation_constants = []
for term in equation_terms:
if term.endswith("x") or term.endswith("y") or term.endswith("z"):
coefficient = term[:-1].strip()
equation_coefficients.append(coefficient)
else:
constant = term.strip()
equation_constants.append(constant)
coefficients.append(equation_coefficients)
constants.append(equation_constants)
# 构建符号变量
x, y, z = sp.symbols('x y z')
# 构建方程组
equations = []
for i in range(3):
equation = sp.Eq(coefficients[i][0]*x + coefficients[i][1]*y + coefficients[i][2]*z, constants[i][0])
equations.append(equation)
# 解方程组
solution = sp.solve(equations, (x, y, z))
# 输出解
print("方程的解为:")
for variable, value in solution.items():
print(variable, "=", value)
```
阅读全文