Use numpy to fit polynomials to known sample points

0. Import related packages:

import matplotlib.pyplot as plt
import numpy as np

1. Suppose there are the following sample points:

#使用随机数产生样本点
x=[1,2,3,4,5,6,7,8,9,10]
y=[2,-25,16,3,35,6,91,-39,20,0]
print("样本点横坐标为:")
print(x)
print("样本点纵坐标为:")
print(y)

Insert picture description here
It is drawn into a scatter chart like this:
Insert picture description here

2. We use numpy to fit these sample points. In this article, we fit the function into a polynomial function. (Core steps)

#使用numpy中的多项式拟合来拟合样本服从的函数。
#下面分别假设多项式最高次数为4,7,8。从而进行对比拟合效果。
degree=[4,7,8]
#每一个最高次数degree对应一个多项式函数,因此创建一个函数数组。
f=[]
for i in range(3):
    #拟合
    model=np.polyfit(x,y,degree[i])
    #通过拟合的模型获得这个多项式函数np.poly1d(model)。
    f.append(np.poly1d(model))
    #打印这个函数
    print(f[i])

The results are as follows:
Insert picture description here
3. Draw a chart and check the fit.

#开始绘制。
colors=["r","g","orange","purple","pink"]
#生成1000个点在区间[1,10],利用拟合结果f(x)得到y。绘制折线图,由于密密麻麻,所以看起来就像函数图像了。
testx=np.linspace(1,10,1000)
plt.figure(figsize=(20,8),dpi=80)
for i in range(3):
    plt.plot(testx,f[i](testx),label=degree[i],color=colors[i])

plt.scatter(x,y,label="o")    
plt.legend()
plt.show()

Insert picture description here

in conclusion

The higher the degree of the polynomial, the better the fit.

Guess you like

Origin blog.csdn.net/qq_43391414/article/details/115005517