请使用python写出高斯消元法的代码
时间: 2024-05-02 21:21:49 浏览: 100
以下是高斯消元法的Python代码:
```python
def gauss_elimination(A, b):
n = len(A)
# 前向消元
for i in range(n):
# 选取主元
pivot = A[i][i]
for j in range(i+1, n):
if abs(A[j][i]) > abs(pivot):
pivot = A[j][i]
A[i], A[j] = A[j], A[i]
b[i], b[j] = b[j], b[i]
# 消元
for j in range(i+1, n):
factor = A[j][i] / A[i][i]
for k in range(i+1, n):
A[j][k] -= factor * A[i][k]
b[j] -= factor * b[i]
# 回带求解
x = [0] * n
for i in range(n-1, -1, -1):
x[i] = b[i]
for j in range(i+1, n):
x[i] -= A[i][j] * x[j]
x[i] /= A[i][i]
return x
```
其中,A为系数矩阵,b为常数向量,返回值为解向量x。
阅读全文