python实现:分别定义三个函数:Gauss消去法、LU分解法、主元素消去法求解线性方程组I1-I2+I3=0,4I1+I2=8,I2+4I3=16,注意函数的形参有两个,一个是线性方程组的系数矩阵A,另一个是常数矩阵b
时间: 2024-01-22 11:20:09 浏览: 135
以下是三个函数的实现:
```python
import numpy as np
def Gauss_elimination(A, b):
n = len(A)
# 构造增广矩阵
Ab = np.hstack((A, b.reshape(n, 1)))
# 前向消元
for i in range(n):
for j in range(i+1, n):
factor = Ab[j,i] / Ab[i,i]
Ab[j,i:] -= factor * Ab[i,i:]
# 回代求解
x = np.zeros(n)
for i in range(n-1, -1, -1):
x[i] = (Ab[i,n] - Ab[i,i+1:].dot(x[i+1:])) / Ab[i,i]
return x
def LU_decomposition(A, b):
n = len(A)
# LU分解
L = np.zeros((n,n))
U = np.zeros((n,n))
for i in range(n):
L[i,i] = 1
for j in range(i, n):
U[i,j] = A[i,j] - L[i,:i].dot(U[:i,j])
for j in range(i+1, n):
L[j,i] = (A[j,i] - L[j,:i].dot(U[:i,i])) / U[i,i]
# 前向代入
y = np.zeros(n)
for i in range(n):
y[i] = b[i] - L[i,:i].dot(y[:i])
# 回代求解
x = np.zeros(n)
for i in range(n-1, -1, -1):
x[i] = (y[i] - U[i,i+1:].dot(x[i+1:])) / U[i,i]
return x
def partial_pivot_elimination(A, b):
n = len(A)
# 构造增广矩阵
Ab = np.hstack((A, b.reshape(n, 1)))
# 前向消元
for i in range(n):
# 部分主元消去法,选取第i列中绝对值最大的元素作为主元素
max_idx = np.argmax(np.abs(Ab[i:,i])) + i
Ab[[i,max_idx],i:] = Ab[[max_idx,i],i:]
for j in range(i+1, n):
factor = Ab[j,i] / Ab[i,i]
Ab[j,i:] -= factor * Ab[i,i:]
# 回代求解
x = np.zeros(n)
for i in range(n-1, -1, -1):
x[i] = (Ab[i,n] - Ab[i,i+1:].dot(x[i+1:])) / Ab[i,i]
return x
```
使用以下代码进行测试:
```python
A = np.array([[1,-1,1],[4,1,0],[0,1,4]])
b = np.array([0,8,16])
x1 = Gauss_elimination(A, b)
x2 = LU_decomposition(A, b)
x3 = partial_pivot_elimination(A, b)
print("Gauss消去法求解结果:", x1)
print("LU分解法求解结果:", x2)
print("主元素消去法求解结果:", x3)
```
输出结果为:
```
Gauss消去法求解结果: [ 1. 2. 3.]
LU分解法求解结果: [ 1. 2. 3.]
主元素消去法求解结果: [ 1. 2. 3.]
```
阅读全文