import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
# --------------------------------------------------------------------------------
def chi2_fit():
#-- set data points
xm = np.array([.05,0.36,0.68,0.80,1.09,1.46,1.71,1.83,2.44,2.09,3.72,4.36,4.60])
ym = np.array([0.35,0.26,0.52,0.44,0.48,0.55,0.66,0.48,0.75,0.70,0.75,0.80,0.90])
ye = np.array([0.06,0.07,0.05,0.05,0.07,0.07,0.09,0.1,0.11,0.1,0.11,0.12,0.1])
#-- least-squares fit with scipy.optimize.curve_fit
p, cov = curve_fit( poly2, xm, ym, sigma=ye, absolute_sigma=True )
print "Fit parameters:\n", par
print "Covariance matrix:\n", cov
#-- plot data and fit result
xp = np.linspace( 0., 5., 100 )
ffit = poly2(xp, p[0], p[1], p[2])
plt.errorbar(xm, ym, yerr=ye, fmt='o')
plt.plot( xp, ffit, '-' )
plt.xlim( 0, 5 )
plt.ylim( 0, 1 )
plt.show()
#-- define fit function
def poly2(x, a=1., b=0., c=0.):
return a * x**2 + b * x + c
if __name__ == '__main__': # –-----------
chi2_fit()
curvefit_example.py
Tool curve_fit aus scipy.optimize
zur χ2-Anpassung und numerischen Optimierung