フーリエ級数展開の例3

Clear[f]; f[x_] := 1 /; -1 < x < 0; 
    f[x_] := -1 /; -2 < x < -1; 
    f[x_] := 1 /; -3 < x < -2; f[x_] := -1 /; 0 < x < 1; 
    f[x_] := 1 /; 1 < x < 2; f[x_] := -1 /; 2 < x < 3; 
    Plot[f[x], {x, -3, 3}, AspectRatio -> Automatic, 
      PlotRange -> {-2, 2}, PlotStyle -> Hue[0.6]]

Clear[a]; a[m_] := 0; Clear[b]; 
    b[m_] := (2/(m π )) ((((-1))^m) - 1); 
    Clear[S]; 
    S[n_, x_] := 
      a[0] + (∑_(k = 1)^n)(a[k]*Cos[k*x*π] + 
              b[k]*Sin[k*x*π]); Clear[G]; 
    G[n_] := Plot[{S[n, x], f[x]}, {x, -3, 3}, 
        PlotStyle -> {Hue[0.0], Hue[0.6]}, 
        AspectRatio -> Automatic, 
        PlotRange -> {{-3, 3}, {-2, 2}}]; {S[1, x], 
      S[3, x]}

Do[G[n], {n, 1, 30, 2}]