フーリエ級数展開の例2

Clear[f]; f[x_] := 1 /; -π < x < 0; 
    f[x_] := -1 /; -2 π < x < -π; 
    f[x_] := 1 /; -3 π < x < -2 π; 
    f[x_] := -1 /; 0 < x < π; f[x_] := 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}]