x = np.array([x for x in range(1, 31)]) y = np.array([9, 10, 11, 12, 13, 14, 13, 12, 11, 9, 10, 11, 12, 13, 14, 12, 11, 10, 9, 8, 7, 8, 9, 11, 9, 7, 6, 5, 3, 1])对上述数据进行10次最小二乘法拟合多项式,分100段的python代码,并做图
时间: 2023-09-07 18:13:41 浏览: 133
最小二乘法python代码示例
以下是对给定数据进行10次最小二乘法拟合多项式的代码,并绘制图表:
```python
import numpy as np
import matplotlib.pyplot as plt
# 数据
x = np.array([x for x in range(1, 31)])
y = np.array([9, 10, 11, 12, 13, 14, 13, 12, 11, 9, 10, 11, 12, 13, 14, 12, 11, 10, 9, 8, 7, 8, 9, 11, 9, 7, 6, 5, 3, 1])
# 拟合多项式
z = np.polyfit(x, y, 10)
p = np.poly1d(z)
# 绘图
xp = np.linspace(1, 30, 100)
plt.plot(x, y, '.', xp, p(xp), '-')
plt.show()
```
运行上述代码将得到一张拟合曲线与原始数据散点图的图表。
阅读全文