给我一段LU分解求解方程组的python代码,并计算系数矩阵的范数,给出例子
时间: 2024-03-04 19:49:17 浏览: 38
以下是使用LU分解求解方程组并计算系数矩阵的范数的Python代码:
```python
import numpy as np
from numpy.linalg import norm
# LU分解求解方程组
def lu_solve(A, b):
n = len(A)
L = np.zeros((n, n))
U = np.zeros((n, n))
for j in range(n):
L[j][j] = 1.0
for i in range(j + 1):
s1 = sum(U[k][j] * L[i][k] for k in range(i))
U[i][j] = A[i][j] - s1
for i in range(j, n):
s2 = sum(U[k][j] * L[i][k] for k in range(j))
L[i][j] = (A[i][j] - s2) / U[j][j]
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
# 计算矩阵的范数
def matrix_norm(A):
return norm(A, ord=2)
# 示例
A = np.array([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
b = np.array([1, 2, 3])
x = lu_solve(A, b)
norm_A = matrix_norm(A)
print("系数矩阵的范数为:", norm_A)
print("方程组的解为:", x)
```
示例输出:
```
系数矩阵的范数为: 9.37219246817244
方程组的解为: [-1. 2. -1.]
```
阅读全文