将着两段代码整合(定义两个函数:一个时高斯消去法、一个是LU分解,另外将矩阵的表示方法由增广矩阵A变成稀系数矩阵和另外一个矩阵):#Gauss消去法 import numpy as np # 构造增广矩阵 A = np.array([[1, -1, 1, 0], [4, 1, 0, 8], [0, 1, 4, 16]],dtype=float) # 高斯消元过程 n = len(A) for i in range(n): # 主元归一化 if A[i][i] == 0: print("主元为0,无法进行消元") break A[i] = A[i] / A[i][i] for j in range(i + 1, n): A[j] = A[j] - A[i] * A[j][i] # 回代过程 x = np.zeros(n, dtype=float) for i in range(n - 1, -1, -1): x[i] = A[i][-1] - np.dot(A[i][i + 1:-1], x[i + 1:]) print("线性方程组的解为:", x) #LU分解 import numpy as np # 构造增广矩阵 A = np.array([[1, -1, 1, 0], [4, 1, 0, 8], [0, 1, 4, 16]], dtype=float) # LU分解 n = len(A) L = np.zeros((n, n)) U = np.zeros((n, n)) for i in range(n): # 计算L的第i列和U的第i行 for j in range(i, n): U[i][j] = A[i][j] - sum(L[i][k] * U[k][j] for k in range(i)) for j in range(i+1, n): L[j][i] = (A[j][i] - sum(L[j][k] * U[k][i] for k in range(i))) / U[i][i] L[i][i] = 1 # 解方程 b = A[:, -1] y = np.zeros(n) for i in range(n): y[i] = b[i] - sum(L[i][j] * y[j] for j in range(i)) x = np.zeros(n) for i in range(n-1, -1, -1): x[i] = (y[i] - sum(U[i][j] * x[j] for j in range(i+1, n))) / U[i][i] print(x)
时间: 2023-11-13 15:04:14 浏览: 75
gus2.rar_矩阵高斯消去_高斯消去
好的,下面是整合后的代码,其中包括高斯消去法和LU分解两个函数,以及对应的矩阵表示方法:
```python
import numpy as np
def gaussian_elimination(A, b):
"""
高斯消去法求解线性方程组 Ax=b
Args:
A: 系数矩阵
b: 常数矩阵
Returns:
x: 解向量
"""
n = len(A)
# 构造增广矩阵
Ab = np.column_stack((A, b))
# 高斯消元过程
for i in range(n):
# 主元归一化
if Ab[i][i] == 0:
print("主元为0,无法进行消元")
break
Ab[i] = Ab[i] / Ab[i][i]
for j in range(i + 1, n):
Ab[j] = Ab[j] - Ab[i] * Ab[j][i]
# 回代过程
x = np.zeros(n)
for i in range(n - 1, -1, -1):
x[i] = Ab[i][-1] - np.dot(Ab[i][i + 1:-1], x[i + 1:])
return x
def LU_decomposition(A, b):
"""
LU分解求解线性方程组 Ax=b
Args:
A: 系数矩阵
b: 常数矩阵
Returns:
x: 解向量
"""
n = len(A)
# LU分解
L = np.zeros((n, n))
U = np.zeros((n, n))
for i in range(n):
# 计算L的第i列和U的第i行
for j in range(i, n):
U[i][j] = A[i][j] - sum(L[i][k] * U[k][j] for k in range(i))
for j in range(i+1, n):
L[j][i] = (A[j][i] - sum(L[j][k] * U[k][i] for k in range(i))) / U[i][i]
L[i][i] = 1
# 解方程
y = np.zeros(n)
for i in range(n):
y[i] = b[i] - sum(L[i][j] * y[j] for j in range(i))
x = np.zeros(n)
for i in range(n-1, -1, -1):
x[i] = (y[i] - sum(U[i][j] * x[j] for j in range(i+1, n))) / U[i][i]
return x
# 稀疏矩阵表示方法
from scipy.sparse import csc_matrix
# 构造系数矩阵
data = np.array([1, 4, 1, -1, 1, 1, 4, 0, 8, 16])
row = np.array([0, 1, 1, 2, 2, 0, 1, 2, 0, 1])
col = np.array([0, 1, 3, 1, 2, 2, 3, 2, 3, 3])
A_sparse = csc_matrix((data, (row, col)), shape=(3, 4)).toarray()
# 构造常数矩阵
b = np.array([0, 8, 16])
# 高斯消去法求解
x1 = gaussian_elimination(A_sparse, b)
print("高斯消去法求解线性方程组 Ax=b 的解为:", x1)
# LU分解求解
x2 = LU_decomposition(A_sparse, b)
print("LU分解求解线性方程组 Ax=b 的解为:", x2)
```
其中,稀疏矩阵的构造使用了scipy库里的csc_matrix()函数,将data、row、col三个数组作为输入,构造出一个csr_matrix对象,然后再将其转换为普通的numpy数组。
阅读全文