# [SciPy-user] Fitting a polynomial to data

Thu Jun 30 15:46:36 CDT 2005

```CJ Fleck wrote:
> I have some data points that I'd like to fit a polynomial to.  I have
> a gut feeling that this can be done with scipy, but I'm not sure how.
> Admitadly, my math skills are a bit lacking and I'm not real sure how

have a look at polyfit in matplotlib, which wraps the needed functionality in
one little, easy to use routine for you.

In [1]: polyfit?
Type:           function
Base Class:     <type 'function'>
String Form:    <function polyfit at 0x40ee180c>
Namespace:      Interactive
File:           /usr/lib/python2.3/site-packages/matplotlib/mlab.py
Definition:     polyfit(x, y, N)
Docstring:
Do a best fit polynomial of order N of y to x.  Return value is a
vector of polynomial coefficients [pk ... p1 p0].  Eg, for N=2

p2*x0^2 +  p1*x0 + p0 = y1
p2*x1^2 +  p1*x1 + p0 = y1
p2*x2^2 +  p1*x2 + p0 = y2
.....
p2*xk^2 +  p1*xk + p0 = yk

Method: if X is a the Vandermonde Matrix computed from x (see
http://mathworld.wolfram.com/VandermondeMatrix.html), then the
polynomial least squares solution is given by the 'p' in

X*p = y

where X is a len(x) x N+1 matrix, p is a N+1 length vector, and y
is a len(x) x 1 vector

This equation can be solved as

p = (XT*X)^-1 * XT * y

where XT is the transpose of X and -1 denotes the inverse.

http://mathworld.wolfram.com/LeastSquaresFittingPolynomial.html,
but note that the k's and n's in the superscripts and subscripts
on that page.  The linear algebra is correct, however.