python完全消元的高斯消元法
时间: 2023-12-08 20:39:30 浏览: 69
以下是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_row = i
for j in range(i+1, n):
if abs(Ab[j, i]) > abs(Ab[max_row, i]):
max_row = j
Ab[[i, max_row]] = Ab[[max_row, 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] - np.dot(Ab[i, i+1:n], x[i+1:n])) / Ab[i, i]
return x
# 测试
A = np.array([[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7]])
b = np.array([10, 11, 12, 13])
x = gauss_elimination(A, b)
print('高斯消元法,最终的解X_i(角标从小到大):{}'.format(x))
```
运行结果为:
```
高斯消元法,最终的解X_i(角标从小到大):[ 1. 2. 3. -2.]
```
阅读全文