Fitting data with python
Jump to navigation
Jump to search
The basic syntax is the following: <source lang="py">
- !/usr/bin/python
from scipy import optimize from numpy import array
- your data as lists
x = [0.0, 1.0, 2.0, 3.0] y = [1.0, 0.5, 0.0, -1.0]
- define a fitting function and the corresponding error function that must be minimized
- use the lambda shortcut or define standard functions with def fit():
- p is the list of parameters
fit = lambda p, x: p[0] + p[1]*(x) + p[2]*(x)**2 err = lambda p, x, y: fit(p,x) - y
- initial guess
p0 = [1.0,1.0,1.0]
- calls optimize.leastsq to find optimal parameters, converts lists into numpy.array on the fly
p, success = optimize.leastsq(err, p0, args=(array(x), array(y)), ftol=5e-9, xtol=5e-9)
- some info about convergence is in success and the optimized parameters in p
</source>