python 拟合 leastsq 最小二乘
python 拟合 leastsq 最小二乘
scipy库提供了函数leastsq函数用于非常规函数的参数拟合
代码实现如下:
import numpy as np
from scipy.optimize import leastsq
#dainiheshuju
data_x = np.array([2.22867,4.44599,10.20322,6.13807])
data_y = np.array([0.16449,0.23483,0.3031,0.25519])
def reso_mcnp(E,p0,p1,c):
return p0 + np.sqrt(p1*(E+c*E*E))
def error(p,x,y):
p0,p1,c = p
return reso_mcnp(x,p0,p1,c)-y
pp = [1,1,1]
Para = leastsq(error,pp,args=(data_x,data_fwhm))
p0,p1,c = Para[0]
print(Para)
Y_reso = reso_mcnp(X_E,p0,p1,c)
plt.figure(figsize=(12,9))
plt.scatter(data_x,data_fwhm)
plt.plot(X_E,Y_reso)
plt.show()
拟合获取了p0、p1、c三个参数,打印参数如下:
(array([-0.01536602, 0.01614392, -0.03796763]), 1)
拟合效果如图