最小二乘线性拟合二次函数曲线的程序代码
时间: 2023-02-19 07:10:46 浏览: 117
下面是一个最小二乘线性拟合二次函数曲线的代码,该代码使用 Python 编写:
```python
import numpy as np
import matplotlib.pyplot as plt
# 构造数据点
x = np.array([0, 1, 2, 3, 4, 5])
y = np.array([1, 2, 1, 2, 1, 2])
# 构造二次函数模型
A = np.array([x**2, x, np.ones(len(x))]).T
# 最小二乘求解
a, b, c = np.linalg.lstsq(A, y, rcond=None)[0]
# 生成拟合曲线
x_fit = np.linspace(x.min(), x.max(), 1000)
y_fit = a * x_fit**2 + b * x_fit + c
# 画图
plt.scatter(x, y)
plt.plot(x_fit, y_fit, 'r')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
```
这段代码对于一组 `x` 和 `y` 的数据点,构造一个二次函数的模型,使用最小二乘法求解该模型的系数,最后画图展示拟合结果。
阅读全文
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)