给我一段高斯消元法的python代码
时间: 2023-07-10 20:08:41 浏览: 50
高斯列消元法代码
以下是高斯消元法的 Python 代码实现:
```python
import numpy as np
def gaussian_elimination(A, b):
n = len(A)
for i in range(n):
# Find pivot row and swap
max_row = i
for j in range(i+1, n):
if abs(A[j][i]) > abs(A[max_row][i]):
max_row = j
A[i], A[max_row] = A[max_row], A[i]
b[i], b[max_row] = b[max_row], b[i]
# Eliminate
for j in range(i+1, n):
scale = A[j][i] / A[i][i]
b[j] -= scale * b[i]
for k in range(i, n):
A[j][k] -= scale * A[i][k]
# Back substitution
x = np.zeros(n)
for i in range(n-1, -1, -1):
x[i] = (b[i] - np.dot(A[i][i+1:], x[i+1:])) / A[i][i]
return x
```
其中,`A` 是系数矩阵,`b` 是常数向量。在函数中,首先进行了行交换以确保主元素是最大的。然后进行消元操作,最后使用回代法计算出解向量 `x`。
阅读全文