HW1, EECS 207A. UCI Fall 2004
by Nasser Abbasi

Problem

Compute the Fourier Coefficients for y = 
      (x^2) .  Plot and Verify the answer

Solution

This below show how to do this. From definition of fourier coefficients, we calculate the coefficients for up to some fixed n. Then plot f[x] and the approximated f[x] and compare the two functions on the same plot.  I also show Fouries approximation for 2 other functions, the sawtooth and the square function.

Clear["Global`*"];

    
<< 
      Graphics`Legend`

 (* 
      define the functions itself we want to approximate*) 
 (*f[x_] := 
        (x^2)  howework function *) 

     (*f[x_] := 
        Which[-Pi ≤ x < 0, 0, 
          0 ≤ x ≤ (Pi/2), 1, 
          (Pi/2) ≤ x ≤ Pi, 0];  
      square*) 
f[x_] := 
      Which[-Pi ≤ x < 0, x, 0 ≤ x < Pi, 
        x];    (*sawtooth*) 

 
denomC = 
      Simplify[(∫_(-Pi)^Pi) Cos[n x]^2 \[DifferentialD]x, 
        Element[n, Integers]];
denomS = 
        Simplify[(∫_(-Pi)^Pi) Sin[n x]^2 \[DifferentialD]x, 
          Element[n, Integers]];

  

a[
          n_] := ((NIntegrate[ f[x] Cos[n x], {x, -Pi, Pi}]  )/denomC);
 

b[n_] := 
        NIntegrate[ f[x] Sin[n x], {x, -Pi, Pi}]/denomS;

 (* define ff[x],  
      the fourier series approximation *) 
ff[x_, k_Integer] := 
        a[0]/2 +  (∑_(n = 1)^k)(an[[
                  n]] 
                Cos[n x]) +  (∑_(n = 1)^k)(bn[[
                  n]] 
                Sin[n x]); 

maxn = 
      10;    (*max number of terms to try *) 

 (* 
      create and print the coeff .  
          tables to use *) 
an = 
      Chop[N[Table[a[n], {n, 1, maxn}] ]];
bn = 
        Chop[N[Table[
              b[n], {n, 1, 
                maxn}] ]]; 
 
Print["a[n] and b[n] Fourier coefficients for n up to ", 
        maxn];
\(\(\(TableForm[
      Table[{i - 1, an[[i]], 
          bn[[i]]}, {i, 1, maxn}], 
      TableHeadings -> {None, {"n", "a[n]", "b[n]"}}]\)\(
\)
    \)\ \)
g = 
        Plot[Evaluate[f[x]], {x, - Pi,  Pi}, 
          PlotStyle -> {Thickness[0.01]}, 
          Ticks -> {{-Pi, -Pi/2, 0, Pi/2, Pi}, Automatic}, 
          PlotRange -> {-Pi, Pi}, 
          DisplayFunction -> Identity];
g2 = Table[i, {i, 1, maxn}];

    
\(\(\(For[k = 1, k < maxn, 
        k = k + 1; \ 
r = 
          Plot[Evaluate[ff[x, k]], {x, \(-Pi\), \ 
              Pi}, 
Ticks -> {{\(-Pi\), \(-Pi\)/2, 0, 
                  Pi/2, Pi}, 
                Automatic}, 
PlotRange -> {\(-Pi\), 
                Pi}, 
DisplayFunction -> 
              Identity]; 

g2[[k]] = 
          Show[{r, g}, 
            PlotLabel -> {"Approximation  for number of terms = ", 
                k}, DisplayFunction -> $DisplayFunction]; 

Print["
"]
];\)\(
\)
    \)\)