背景:
使用scipy拟合一元二次函数。
参考:
HYRY Studio-《用Python做科学计算》
代码:
import numpy as np
from scipy.optimize import leastsq
import pylab as pl
def func(x,p):
"""
数组拟合函数
"""
A,k,theta = p
return A*(x-k)**2+theta
def 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()
结果:
(貌似这里的求解方法用了智能算法,因为每次的结果都有细小差异。具体资料没见到,以后有精力再找)
真实参数: [10.0, 1, 2.0]
拟合参数: [ 11.06873474 0.99709893 1.49107462]