用python实现高斯列主元消元法
时间: 2024-06-13 20:07:23 浏览: 85
以下是使用Python实现高斯列主元消元法的代码示例:
```python
import numpy as np
# 高斯列主元消元法
def gauss_elimination(A, b):
n = len(A)
# 构造增广矩阵
Ab = np.concatenate((A, b.reshape(n, 1)), axis=1)
# 消元过程
for i in range(n):
# 选主元
max_index = abs(Ab[i:, i]).argmax() + i
if Ab[max_index, i] == 0:
raise ValueError("Matrix is singular.")
# 交换行
if max_index != i:
Ab[[i, max_index]] = Ab[[max_index, i]]
# 消元
for j in range(i+1, n):
Ab[j] = Ab[j] - Ab[i] * Ab[j, i] / Ab[i, i]
# 回代过程
x = np.zeros(n)
for i in range(n-1, -1, -1):
x[i] = (Ab[i, -1] - Ab[i, :-1] @ x) / Ab[i, i]
return x
# 测试
A = np.array([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
b = np.array([1, 2, 3])
x = gauss_elimination(A, b)
print(x) # 输出:[-1. 2. 0.]
```
阅读全文