顺序 Gauss 消元法和列主元 Gauss 消元法求解python
时间: 2023-11-08 22:10:50 浏览: 83
以下是使用 Python 实现顺序 Gauss 消元法和列主元 Gauss 消元法的代码示例:
```python
import numpy as np
# 顺序 Gauss 消元法
def gaussian_elimination(A, b):
n = len(b)
for i in range(n):
# 找到主元
for j in range(i+1, n):
if abs(A[i][i]) < abs(A[j][i]):
A[i], A[j] = A[j], A[i]
b[i], b[j] = b[j], b[i]
# 消元
for j in range(i+1, n):
ratio = A[j][i] / A[i][i]
for k in range(i, n):
A[j][k] -= ratio * A[i][k]
b[j] -= ratio * b[i]
# 回代
x = np.zeros(n)
for i in range(n-1, -1, -1):
x[i] = (b[i] - np.dot(A[i][i+1:], x[i+1:])) / A[i][i]
return x
# 列主元 Gauss 消元法
def gaussian_elimination_with_pivoting(A, b):
n = len(b)
for i in range(n):
# 找到主元
max_idx = i
for j in range(i+1, n):
if abs(A[j][i]) > abs(A[max_idx][i]):
max_idx = j
# 交换行
A[i], A[max_idx] = A[max_idx], A[i]
b[i], b[max_idx] = b[max_idx], b[i]
# 消元
for j in range(i+1, n):
ratio = A[j][i] / A[i][i]
for k in range(i, n):
A[j][k] -= ratio * A[i][k]
b[j] -= ratio * b[i]
# 回代
x = np.zeros(n)
for i in range(n-1, -1, -1):
x[i] = (b[i] - np.dot(A[i][i+1:], x[i+1:])) / A[i][i]
return x
```
其中,`A` 是系数矩阵,`b` 是常数向量。函数 `gaussian_elimination` 实现顺序 Gauss 消元法,函数 `gaussian_elimination_with_pivoting` 实现列主元 Gauss 消元法。两个函数的返回值均为解向量 `x`。
阅读全文