# -*- coding:utf-8 -*-#! python3import numpy as npfrom scipy.optimize import leastsqimport pylab as pldef func(x,p): """ 数组拟合函数 """ A,k,theta = p return A*(x-k)**2+thetadef residuals(p,y,x): """ 残差 """ return y-func(x,p)x = np.linspace(0,2,100)A,k,theta = 10.,1,2. #真实数据参数y0 = func(x,[A,k,theta]) #真实数据y1 = y0 + 2 * np.random.randn(len(x)) #加入噪声序列p0 = [7.,0.2,1.]plsq = leastsq(residuals,p0,args = (y1,x))print("真实参数:",[A,k,theta])print("拟合参数:",plsq[0]) #试验数据拟合后的参数pl.plot(x,y0,label = "real")pl.plot(x,y1,label = "real+noise")pl.plot(x,func(x,plsq[0]),label = "fitting")pl.legend()pl.show()