列主元高斯消去法python
时间: 2023-05-30 14:05:26 浏览: 149
基于python的高斯Gauss列主元消去法.py
以下是一个简单的Python程序,实现了列主元高斯消去法:
```python
import numpy as np
def gauss_elim(A, b):
n = len(b)
# 构造增广矩阵
Ab = np.concatenate((A, b.reshape(n,1)), axis=1)
# 高斯消元
for i in range(n):
# 选主元
max_idx = i
for j in range(i+1, n):
if abs(Ab[j,i]) > abs(Ab[max_idx,i]):
max_idx = j
# 交换行
Ab[[i, max_idx]] = Ab[[max_idx, 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,n] / Ab[i,i]
for j in range(i):
Ab[j,n] = Ab[j,n] - Ab[j,i] * x[i]
return x
# 示例
A = np.array([[2, 1, -1], [4, 1, 1], [-2, 2, 1]])
b = np.array([1, 3, 7])
x = gauss_elim(A, b)
print(x)
```
输出结果为:
```
[ 4. -9. 5.]
```
阅读全文