多项式拟合

来源:互联网 发布:mysql分页是什么 编辑:程序博客网 时间:2024/04/30 09:14

用6项多项式拟合sin函数:

要求数据点为10个(含噪声)

程序

import numpy as npimport pylab as plfrom scipy.optimize import leastsqn=6def real_func(x):    return np.sin(2*np.pi*x)def fit_func(p,x):    f=np.poly1d(p)    return f(x)def residuals_func(p,y,x):#残差    ret=fit_func(p,x)-y    return retx=np.linspace(0,1,10)x_points=np.linspace(0,1,1000)y0=real_func(x)y1=[np.random.normal(0,0.1)+y for y in y0]#构造含噪数据点p_init=np.ones([1,n])*np.random.normal()print(p_init)plsq=leastsq(residuals_func,p_init,args=(y1,x))#拟合参数print("fitting parameter:",plsq[0])pl.plot(x_points,real_func(x_points),label="real")pl.plot(x_points,fit_func(plsq[0],x_points),label="fitted curve")pl.plot(x,y1,"bo",label="with noise")pl.legend()pl.show()

0 0
原创粉丝点击