FITTING A FOURIER SERIES TO A SET OF DATA

The following example illustrates the use of NonlinearFit to fit a Fourier series to a set of data we believe to be periodic.

Some data

We begin by creating some fake data for our example.

data=Table[{i,Cos[i]+3 Sin[i] + Random[Real,{-.05,.05}]},{i,1,80,.5}];

Loading the package

NonlinearFit is a function contained in the package Statistics`NonlinearFit. To use the function we need to load the package. The following command loads the package.

<<Statistics`NonlinearFit`

The function

The function we will use is NonlinearFit. It requires, in addition to the data points the following information.

The model

All fit functions require us to provide a model. We will use the following model for this example. The parameters in this model are the b[i] and c[i]. You can see the form of the model by removing the semi-colon at the end of the expression.

model = a0+Sum[b[i]*Cos[i(t-c[i])],{i,1,39}];

The parameters

We also need to specify the parameters in our model. In this case the easiest way to construct such a list is with the Table function.

params= Join[{a0},Table[b[i],{i,1,39}],Table[c[i],{i,1,39}]];

Using the NonlinearFit function

Now we put our data, model, parameter list and the names of our variables in the function to get our answer. We have applied Chop below to eliminate terms of very small size:

?NonlinearFit

The fitted function is very long so I have suppressed the output.

B[t_]=Chop[NonlinearFit[data,model,t,params]];

Looking at our solution

We can use plot functions to get an idea of how well our function fits the data. First a plot of the data.

g1=ListPlot[data,PlotJoined->True,PlotStyle->RGBColor[1,0,0]]

g2=Plot[B[t],{t,1,80},PlotStyle->RGBColor[0,1,0]]

The plot suggests our function to be a good fit.

Show[{g1,g2},ImageSize -> 540]