Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fit polynomial to data with error bars

I am currently using numpy.polyfit(x,y,deg) to fit a polynomial to experimental data. I would however like to fit a polynomial that uses weighting based on the errors of the points.

I have found scipy.curve_fit which makes use of weights and I suppose I could just set the function, 'f', to the form a polynomial of my desired order, and put my weights in 'sigma', which should achieve my goal.

I was wondering is there another, better way of doing this?

Many Thanks.

like image 533
Jdog Avatar asked Jul 12 '11 10:07

Jdog


2 Answers

For weighted polynomial fitting you can use:

numpy.polynomial.polynomial.polyfit(x, y, deg, rcond=None, full=False, w=weights)

see http://docs.scipy.org/doc/numpy/reference/generated/numpy.polynomial.polynomial.polyfit.html

Important to note that in this function the weights should not be supplied as 1/variance (which is the usual form in many weighted applications), but as 1/sigma

Although curve_fit and leastsq are much more general and powerful optimization tools than polyfit (in that they can fit just any function), polyfit has the advantage that it yields an (exact) analytical solution and is therefore probably much faster than iterative approximation methods like curve_fit and leastsq - especially in the case of fitting polynomials to multiple sets of y-data (obtained at the same x-vector)

Update: As of numpy version 1.7, numpy.polyfit also takes weights as an input (which ideally should be supplied as 1/sigma, not 1/variance)

like image 177
Rolf Bartstra Avatar answered Sep 22 '22 14:09

Rolf Bartstra


Take a look at http://scipy-cookbook.readthedocs.io/items/FittingData.html in particular the section 'Fitting a power-law to data with errors'. It shows how to use scipy.optimize.leastsq with a function that includes error weighting.

like image 37
Bernhard Avatar answered Sep 25 '22 14:09

Bernhard