use python to solve equations
2025-04-08 15:40:13

在 Python 中,可以用以下几个库来求解方程:

  1. SymPy(符号求解)
1
2
3
4
5
6
from sympy import symbols, Eq, solve

x = symbols('x')
eq = Eq(x**2 - 4, 0) # x² - 4 = 0
solutions = solve(eq, x)
print(solutions) # 输出: [-2, 2]
  1. NumPy(求解线性方程组)
1
2
3
4
5
6
import numpy as np

A = np.array([[3, 2], [1, 2]])
b = np.array([5, 2])
x = np.linalg.solve(A, b)
print(x) # 输出: 线性方程组的解
  1. SciPy(数值解)
1
2
3
4
5
6
7
from scipy.optimize import fsolve

def func(x):
return x**2 - 4 # 目标是找到 f(x) = 0 的解

root = fsolve(func, x0=[1]) # x0 为初始猜测值
print(root) # 输出: [2.]

使用 SymPy 进行符号求解非常适合解析求解方程。这里是一些常见的例子.

1. 求解一元方程

1
2
3
4
5
6
from sympy import symbols, Eq, solve

x = symbols('x')
eq = Eq(x**2 - 4, 0) # 方程 x² - 4 = 0
solutions = solve(eq, x)
print(solutions) # 输出: [-2, 2]

2. 求解多个方程(联立方程组)

1
2
3
4
5
6
7
8
from sympy import symbols, Eq, solve

x, y = symbols('x y')
eq1 = Eq(2*x + y, 1) # 2x + y = 1
eq2 = Eq(x - y, 3) # x - y = 3

solutions = solve((eq1, eq2), (x, y))
print(solutions) # 输出: {x: 2, y: -1}

3. 求解三次及以上方程

1
2
3
4
5
6
from sympy import symbols, Eq, solve

x = symbols('x')
eq = Eq(x**3 - 6*x**2 + 11*x - 6, 0) # (x - 1)(x - 2)(x - 3) = 0
solutions = solve(eq, x)
print(solutions) # 输出: [1, 2, 3]

4. 含参数的方程

1
2
3
4
5
6
from sympy import symbols, Eq, solve

x, a = symbols('x a')
eq = Eq(a*x**2 - 4, 0) # a*x² - 4 = 0
solutions = solve(eq, x)
print(solutions) # 输出: [-2/sqrt(a), 2/sqrt(a)]

SymPy 适用于解析求解方程,尤其是代数方程、联立方程或带参数的方程。如果你需要数值解,SciPy 或 NumPy 可能更合适。****

Prev
2025-04-08 15:40:13