n阶列主元高斯消去法py
时间: 2024-06-13 08:07:31 浏览: 89
以下是基于Python的n阶列主元高斯消去法的实现:
```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, 5, 2], [6, 2, 4]])
b = np.array([5, 8, 12])
x = gauss_elimination(A, b)
print(x) # 输出:[-1. 2. 1.]
```
阅读全文