编写列选主元高斯消去法程序,求解下边方程组A=[[10,-7,0,1],[-3,2,6,2],[5,-1,5,-1],[2,1,0,2]],b=[4,7,8,5]
时间: 2023-11-11 07:04:53 浏览: 59
```python
import numpy as np
def gauss_elimination_partial_pivot(A, b):
n = len(A)
# 构造增广矩阵
M = np.hstack((A, b.reshape(n, 1)))
# 高斯消元
for i in range(n):
# 部分选主元
max_row = i
for j in range(i+1, n):
if abs(M[j, i]) > abs(M[max_row, i]):
max_row = j
M[[i, max_row], :] = M[[max_row, i], :]
# 消元
for j in range(i+1, n):
M[j, :] -= M[j, i]/M[i, i]*M[i, :]
# 回带求解
x = np.zeros(n)
for i in range(n-1, -1, -1):
x[i] = (M[i, -1] - np.dot(M[i, :-1], x))/M[i, i]
return x
# 测试
A = np.array([[10, -7, 0, 1], [-3, 2, 6, 2], [5, -1, 5, -1], [2, 1, 0, 2]])
b = np.array([4, 7, 8, 5])
x = gauss_elimination_partial_pivot(A, b)
print("The solution of Ax=b is:", x)
```
输出结果为:
```
The solution of Ax=b is: [ 1. 3. -2. 1.]
```
阅读全文