Previous Up Next

6.27.35  Least-squares polynomial approximation: fitpoly

The fitpoly command is used for replacing tabular data or a function by a polynomial of suitable/specified degree.

Smoothing data: polynomial regression

To find a polynomial that fits tabular data:

Example.
We find a polynomial which best approximates the data infected by noise. The data is produced by evaluating the polynomial f(x)=1/100x4−1/5x3+6x at 100 points between x=1 and x=20.8. The noise is generated by a random, normally-distributed variable.
Input:

f(x):=x^4/100-x^3/5+6x:;
x:=[(1+0.2*k)$(k=0..99)]:;
noise:=randvector(100,randvar(normal,mean=0,stddev=10)):;
y:=apply(f,x)+noise:;
fitpoly(x,y)

We obtain the list of polynomial coefficients, starting with the leading coefficient.
Output:

[0.011665,−0.266955,0.844543,2.44967,3.94846] 

Note that the polynomial of degree 4 is returned (it has five coefficients), which is, in this case, optimal for data smoothing.

When approximating only the data in segment [1,10], we obtain a polynomial of 9th degree (the data curvature is now much smaller and the noise is more prominent).
Input:

length(fitpoly(x,y,1..10))

Output:

10 

To make the approximating polynomial less sensitive to noise, we increase the threshold value tol.
Input:

fitpoly(x,y,t=1..10,threshold=0.05)

Output:

−1.30984955412 t2+9.3259443857 t−2.6482979067 

Alternatively, we could set the parameter length to a smaller value, e.g. 3.

Approximating functions by polynomials

To approximate a continuous function f:[a,b]→ℝ by a polynomial pn of certain degree n which minimizes the error in the sense of L2-norm:


Examples.
Input:

fitpoly(cos(x),0..pi/2,1e-2)

Output:

−0.244320054366 x3−0.336364730985 x2+1.13004492821 x−0.0107731059645 

Input:

f:=exp(-7x)*5x:; g:=fitpoly(f,0..1,degree=8)

Output:

     
 −21.717636069 x8+107.930784832 x7−232.831655404 x6         
 +286.778708741 x5−222.236631985 x4+111.004732684 x3         
 −33.8769709361 x2+4.95239715728 x+0.000500886757642          

The mean absolute error of the above approximation can be estimated as follows.
Input:

sqrt(romberg((f-g)^2,x=0..1))

Output:

9.3456615562×10−5 

Previous Up Next