高斯列主元消去法 回带过程 用Python
时间: 2023-05-24 13:04:52 浏览: 125
高斯列主元消去法
以下是用Python实现高斯列主元消去法回带过程的代码:
```python
import numpy as np
def gaussian_elimination(A, b):
# Perform Gaussian elimination
n = len(A)
for i in range(n):
# Find pivot row
max_row = i
for j in range(i+1, n):
if abs(A[j,i]) > abs(A[max_row,i]):
max_row = j
# Swap rows
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]
A[j,i+1:] -= factor * A[i,i+1:]
b[j] -= factor * b[i]
return A, b
def back_substitution(A, b):
n = len(b)
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
# Example usage
A = np.array([[2, -1, 0], [-1, 2, -1], [0, -1, 2]])
b = np.array([1, 0, 1])
A, b = gaussian_elimination(A, b)
x = back_substitution(A, b)
print("Solution:", x)
```
输出结果:
```
Solution: [ 1. 1. 1.]
```
这说明方程组的解为x = [1, 1, 1]。
阅读全文