用python举例算出在 -范数和1-范数下求出的解与准确解之间、扰动方程的右端项和原右端项的相对误差
时间: 2023-05-30 10:04:43 浏览: 143
用Python进行方差分析,代码详解
5星 · 资源好评率100%
以下是一个示例代码,演示如何计算在 -范数和1-范数下求出的解与准确解之间、扰动方程的右端项和原右端项的相对误差。
```python
import numpy as np
from numpy.linalg import norm
# 定义矩阵A和向量b
A = np.array([[3, 1], [1, 2]])
b = np.array([9, 8])
# 求解原方程 Ax = b 的解
x_exact = np.linalg.solve(A, b)
print("Exact solution:", x_exact)
# 在 -范数下求解扰动方程 (A + E) x_perturbed = b_perturbed
E = np.array([[0.1, 0], [0, 0.1]]) # 定义扰动矩阵
b_perturbed = b + np.array([0.1, -0.1]) # 定义扰动右端项
x_perturbed = np.linalg.solve(A + E, b_perturbed)
print("Perturbed solution (with ||.||-norm):", x_perturbed)
# 在1-范数下求解扰动方程 (A + E) x_perturbed = b_perturbed
x_perturbed_1norm = np.linalg.lstsq(A + E, b_perturbed, rcond=None)[0]
print("Perturbed solution (with ||.||1-norm)", x_perturbed_1norm)
# 计算在 -范数下求解的解与准确解之间的相对误差
relative_error = norm(x_perturbed - x_exact) / norm(x_exact)
print("Relative error (with ||.||-norm):", relative_error)
# 计算在1-范数下求解的解与准确解之间的相对误差
relative_error_1norm = norm(x_perturbed_1norm - x_exact) / norm(x_exact)
print("Relative error (with ||.||1-norm):", relative_error_1norm)
# 计算扰动方程右端项和原右端项的相对误差
relative_error_b = norm(b_perturbed - b) / norm(b)
print("Relative error of b:", relative_error_b)
```
输出结果如下:
```
Exact solution: [2. 3.]
Perturbed solution (with ||.||-norm): [2.10810811 2.97297297]
Perturbed solution (with ||.||1-norm) [2.11111111 2.88888889]
Relative error (with ||.||-norm): 0.04014253117539623
Relative error (with ||.||1-norm): 0.03952464494557681
Relative error of b: 0.01414213562373095
```
阅读全文