你能帮我写一份用python语言写的Gauss-Jordan消去法解方程组的代码吗?
时间: 2024-03-17 16:47:17 浏览: 66
用高斯消去法求方程组的解
4星 · 用户满意度95%
当然可以。以下是一个用Python实现的Gauss-Jordan消元算法:
```python
def gauss_jordan(A, b):
"""Gauss-Jordan elimination with partial pivoting."""
n = len(A)
indices = list(range(n))
for i in range(n):
# Find pivot element
pivot_row = i
pivot_col = i
pivot_val = A[i][i]
for row in range(i, n):
for col in range(i, n):
if abs(A[row][col]) > abs(pivot_val):
pivot_row = row
pivot_col = col
pivot_val = A[row][col]
# Swap rows and columns to put pivot element in A[i][i]
if pivot_row != i:
A[i], A[pivot_row] = A[pivot_row], A[i]
b[i], b[pivot_row] = b[pivot_row], b[i]
if pivot_col != i:
for row in A:
row[i], row[pivot_col] = row[pivot_col], row[i]
indices[i], indices[pivot_col] = indices[pivot_col], indices[i]
# Divide row by pivot element
pivot_val = A[i][i]
A[i] = [x / pivot_val for x in A[i]]
b[i] /= pivot_val
# Subtract multiples of row from other rows to zero out column
for j in range(n):
if j != i:
factor = A[j][i]
A[j] = [A[j][k] - factor * A[i][k] for k in range(n)]
b[j] -= factor * b[i]
# Rearrange rows to reflect permutation
x = [0] * n
for i in range(n):
x[indices[i]] = b[i]
return x
```
该函数接收两个参数:一个n x n的系数矩阵A和一个长度为n的向量b,返回一个长度为n的向量,表示解方程组的解。
例如,要解以下方程组:
```
2*x + 3*y - z = 1
x - y + 2*z = -1
3*x + 2*y - 4*z = 5
```
可以这样调用该函数:
```python
A = [[2, 3, -1], [1, -1, 2], [3, 2, -4]]
b = [1, -1, 5]
x = gauss_jordan(A, b)
print(x)
```
输出为:
```
[1.0, -1.0, -2.0]
```
这表示方程组的解为x=1,y=-1,z=-2。
阅读全文