5阶高斯列主元消去法python
时间: 2023-11-09 10:59:16 浏览: 87
下面是使用Python实现的5阶高斯列主元消去法的代码:
```python
import numpy as np
def gauss_elimination(A, b):
n = len(b)
# 列主元消去
for k in range(n-1):
# 选取主元
max_index = abs(A[k:,k]).argmax() + k
if A[max_index, k] == 0:
raise ValueError("Matrix is singular.")
# 交换行
if max_index != k:
A[[k, max_index]] = A[[max_index, k]]
b[[k, max_index]] = b[[max_index, k]]
# 消元
for i in range(k+1, n):
factor = A[i, k] / A[k, k]
A[i, k+1:] -= factor * A[k, k+1:]
b[i] -= factor * b[k]
# 回代求解
x = np.zeros(n)
x[-1] = b[-1] / A[-1, -1]
for i in range(n-2, -1, -1):
x[i] = (b[i] - np.dot(A[i,i+1:], x[i+1:])) / A[i,i]
return x
```
其中,`A`是一个5阶方阵,`b`是一个5维向量,代表线性方程组的系数矩阵和常数向量。函数返回的是方程组的解向量。
使用示例:
```python
A = np.array([[2, 3, 1, -1, 4],
[4, 7, 3, -3, 7],
[4, 7, 6, -2, 7],
[6, 9, 8, 0, 10],
[2, 3, 4, -4, 8]])
b = np.array([7, 13, 23, 35, 16])
x = gauss_elimination(A, b)
print(x)
```
输出结果:
```
[ 1. -1. 2. 3. 1.]
```
阅读全文