Thursday, July 14, 2011

Polynomial curve fitting

We have seen already how to a fit a given set of points minimizing an error function, now we will see how to find a fitting polynomial for the data using the function polyfit provided by numpy:
from numpy import *
import pylab

# data to fit
x = random.rand(6)
y = random.rand(6)

# fit the data with a 4th degree polynomial
z4 = polyfit(x, y, 4) 
p4 = poly1d(z4) # construct the polynomial 

z5 = polyfit(x, y, 5)
p5 = poly1d(z5)

xx = linspace(0, 1, 100)
pylab.plot(x, y, 'o', xx, p4(xx),'-g', xx, p5(xx),'-b')
pylab.legend(['data to fit', '4th degree poly', '5th degree poly'])
pylab.axis([0,1,0,1])
pylab.show()

Let's see the two polynomials:

5 comments:

  1. I need one that shows the steps please. sorry about the symbols, but I wanted to make sure it was clear that I wanted a calculator for this, some people didn't understand that.

    Actually, is a calculator to calculate simplest polynomial functions with given roots even possible?

    ReplyDelete
  2. Hi nick, maybe I don't get exactly what you need. By the way, if you need more information about the polynomial interpolation you can find out more looking for 'Lagrange interpolation' on any algebra book or at http://en.wikipedia.org/wiki/Polynomial_interpolation . If you need a tool to work with symbolic calculation, I suggest you maxima and (http://maxima.sourceforge.net/) the symbolic matlab toolbox.

    ReplyDelete
  3. como se suman polinomios?

    ReplyDelete
  4. Hi ! I have read your article with much interest.

    In your previous comment, you speak about "Lagrange interpolation" and I remember using this method on a series to get "intermediate" values. I used scipy.interpolate.lagrange for this but this function needs to be given an extract of the series. Indeed, the length of its parameters gives the degree of the polynomial (minus 1 I guess).

    What does polyfit compared to interpolate.lagrange ? Does it select the best points to create what I call the "sub series" ? Thanks for your answer :)

    Pierre.

    ReplyDelete
  5. Hello Pierre, thank for you comment.

    I suggested to nick to begin with Lagrange Interpolation because I thought that he was looking for something that doesn't involve an optimization process.

    As you noticed, the Lagrange interpolation is exact while the polyfit is not. Indeed, polyfit finds the coefficients of a polynomial that fits the data in a least squares sense.

    There's no point selection in polyfit.

    ReplyDelete