python实现最优平方逼近三次多项式
时间: 2023-11-17 16:06:45 浏览: 79
最优平方逼近指在最小二乘意义下,用一个 $n$ 次多项式来拟合给定的 $N$ 个点的函数值,通常使用矩阵运算来解决这个问题。对于三次多项式的情况,可以使用以下代码实现:
```python
import numpy as np
import matplotlib.pyplot as plt
# 给定的点的函数值
x = np.array([1, 2, 3, 4, 5])
y = np.array([3.4, 4.5, 6.2, 7.8, 9.5])
# 构造矩阵
A = np.vstack([x**3, x**2, x, np.ones(len(x))]).T
# 最小二乘解
coeffs = np.linalg.lstsq(A, y, rcond=None)[0]
# 构造拟合曲线
x_fit = np.linspace(1, 5, 100)
y_fit = coeffs[0]*x_fit**3 + coeffs[1]*x_fit**2 + coeffs[2]*x_fit + coeffs[3]
# 绘图
plt.scatter(x, y)
plt.plot(x_fit, y_fit, 'r')
plt.show()
```
其中,`np.vstack([x**3, x**2, x, np.ones(len(x))]).T` 构造了 $4$ 行 $N$ 列的矩阵,其中第 $1$ 行到第 $3$ 行分别是 $x$ 的三次方、平方和一次方项,第 $4$ 行都是 $1$,这样可以将 $A$ 乘上系数向量得到 $y$ 的估计值。`np.linalg.lstsq(A, y, rcond=None)` 求得了最小二乘解,也就是系数向量。最后用得到的系数向量构造拟合曲线并绘图。
阅读全文
相关推荐
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)