Fourier Series

Programming

Clear[c,  s, n, a0]
Off[NIntegrate::"ncvb", NIntegrate::"ploss"]
c[f_,  n_, period_]  :=  (2/period)*
        NIntegrate[
          f[x]* Cos[((2 Pi n  x)/period)],  {x,  0,  
            period}] 
s[f_,   n_, period_]  :=  (2/period)*
        NIntegrate[
          f[x]* Sin[((2 Pi n x)/period)],  {x,  0,  
            period}] 
a0[f_,  period_]  :=  (1/period)*
        NIntegrate[f[x],  {x,  0,  period}]
Clear[S]
S[f_, 
        a_] := ((∑_(n = 1)^a) s[f, n, 
                period] Sin[((2 π n x)/period)]) + 
((∑_(n = 1)^a) c[f, n, 
                period] Cos[((2 π n x)/period)]) + 
        a0[f, period]

Usage:  Suppose f is a periodic function with period  A.  Then the commands
period = A;
h[x_] =  S[  f,   n]
computes the Fourier series of    f    up  to order n.
Here are some examples:

Example 1 --  Sawtooth function

Clear[f]
f[x_]  :=  
        N[x]  /;  Floor[x]  ==  0;
f[x_]   :=  N[f[x  -  Floor[x]]] 
period  =  1;

Plot[f[x],  {x,  -2,  2}]

appr[x_]  =  S[f,  10]

Plot[{appr[x]},  {x,  -2,  2}]

Plot[{f[x],  appr[x]},  {x,  -2,  2}]

Example 2  -  Square wave

g[x_]  :=   1  /;   Floor[x]  ==  
          1
g[x_]  :=  -1  /;  
        Floor[x]  ==  0
g[x_]   :=   g[x  -  2*Floor[x/2]]
period  =  2;

Plot[g[x],  {x,  -2, 2}]

appr[x_]  =  S[g, 10]

Plot[{appr[x]},  {x,  -2,  2}]

Plot[{g[x],  appr[x]},  {x,  -2,  2}]