将着两段代码整合(定义两个函数:一个时高斯消去法、一个是LU分解):#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 浏览: 95
可以将这两段代码整合成一个函数,输入参数为增广矩阵 A,输出为线性方程组的解向量 x。下面是整合后的代码:
```python
import numpy as np
def solve_linear_equations(A):
# 判断A是否为方阵
if A.shape[0] != A.shape[1] - 1:
print("A不是方阵")
return None
# 判断A是否奇异
if np.linalg.det(A[:, :-1]) == 0:
print("A是奇异矩阵")
return None
n = A.shape[0]
# LU分解
L = np.zeros((n, n))
U = np.zeros((n, n))
for i in range(n):
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]
return x
```
你可以直接调用这个函数,如下所示:
```python
A = np.array([[1, -1, 1, 0], [4, 1, 0, 8], [0, 1, 4, 16]], dtype=float)
x = solve_linear_equations(A)
print("线性方程组的解为:", x)
```
阅读全文