python实现高斯消元法
时间: 2023-12-04 22:01:13 浏览: 75
以下是Python实现高斯消元法的代码:
```python
import numpy as np
def gaussian_elimination(A, b):
n = len(A)
# 构造增广矩阵
AB = np.hstack((A, b.reshape(n, 1)))
# 高斯消元
for i in range(n):
# 找到主元
max_index = i
for j in range(i + 1, n):
if abs(AB[j, i]) > abs(AB[max_index, i]):
max_index = j
# 交换行
AB[[i, max_index]] = AB[[max_index, i]]
# 消元
for j in range(i + 1, n):
AB[j] = AB[j] - AB[i] * AB[j, i] / AB[i, i]
# 回带
x = np.zeros(n)
for i in range(n - 1, -1, -1):
x[i] = (AB[i, n] - np.dot(AB[i, i + 1:n], x[i + 1:n])) / AB[i, i]
return x
```
其中,A是系数矩阵,b是常数向量,函数返回解向量x。
相关问题
用Python实现高斯消元法
以下是用Python实现高斯消元法的代码:
```python
import numpy as np
def gauss_elimination(A, b):
n = len(b)
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):
factor = A[j][i] / A[i][i]
b[j] -= factor * b[i]
for k in range(i, n):
A[j][k] -= factor * 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
```
利用python实现高斯消元法
在Python中,我们可以利用numpy库来实现高斯消元法,这是一种线性代数的基础解系求解方法。以下是一个简单的例子:
```python
import numpy as np
def gauss_elimination(matrix):
"""
高斯消元法求解线性方程组
:param matrix: 二维numpy数组,表示系数矩阵,形状为(m, n),m>=n
:return: solution (解向量) 和 pivot (交换行列的索引列表)
"""
m, n = matrix.shape
pivot = list(range(n)) # 存储行交换记录
for i in range(n): # 逐列进行消元
max_row = i # 初始化最大非零元素所在的行
for j in range(i+1, m):
if abs(matrix[j][i]) > abs(matrix[max_row][i]):
max_row = j
# 按需交换行
if max_row != i:
matrix[[i, max_row]] = matrix[[max_row, i]]
pivot[i], pivot[max_row] = pivot[max_row], pivot[i]
# 消元:除当前行的第i个元素
matrix[i] /= matrix[i][i]
for j in range(i+1, m):
factor = matrix[j][i]
matrix[j] -= factor * matrix[i]
# 回带求解
solution = np.zeros((m, 1))
solution[-1] = 1 # 结束行添加1作为常数项
for i in range(m-1, -1, -1):
solution[i] = matrix[i][i+1:]
for j in range(i+1, m):
solution[i] -= matrix[i][j] * solution[j]
return solution, pivot
# 示例
matrix = np.array([[4, 7, 8], [2, 5, 6], [1, 1, 2]])
solution, _ = gauss_elimination(matrix)
print("Solution:", solution)
```
在这个代码里,我们首先设置主元素(对角线元素),然后逐列消除其他元素。最后通过回带算法求解得到解向量。注意,这个版本假设输入矩阵是方阵且秩等于其行数,如果是超过维度的矩阵,还需要额外处理。
阅读全文