# Pointwise convergence of Fourier series: partial sum animation not rendering plot

I'm new to Mathematica (13.3) and I'm attempting to demonstrate the pointwise convergence of the Fourier series for the square wave function f in particular, by showing via Animate/Manipulate that as the number of terms N in the partial sum increases, the plot of the partial sum converges to f.

f[s_] :=
Piecewise[{{Pi, -2 Pi <= s < -Pi}, {Pi, 0 <= s < Pi}, {0, -Pi <= s < 0}, {0, Pi <= s < 2 Pi}}]

k = {-2 Pi, -Pi, 0, Pi, 2 Pi}

plot[m_] :=
Plot[(1/(2 Pi)) Sum[E^(I x n) Integrate[f[s] (E^(-I n s)), {s, -Pi, Pi}], {n, -m, m}], {x, -2 Pi, 2 Pi},
PlotStyle -> {Directive[Blend[{Green, Cyan}, 0.7]]},
PlotRange -> {{-2 Pi, 2 Pi}, {-1/2, Pi + 1/2}},
Ticks -> {k, {0, Pi}},
AxesLabel -> {"x", Row[{Subscript["S", "N"], "f ( x )"}]},
PlotLegends -> {Row[{"N = ", m}]}]

M = Manipulate[plot[t], {t, 0, 50, 1}]

Export["PtWConvergence.png", M, "VideoFrames"]


Edit: Previously the plot did not render for the animation, now the animation generates the plots for N = 0, and then N = 1 but then freezes and aborts. No error messages. I'm looking for how to fix this so that we see as N increases, the plot lines begin to approximate the square wave plot.

I couldn't find relevant help or help that I could understand, so thanks for any you can offer!

• Don't use curly brackets in your expression, they are reserved for List s Nov 27, 2023 at 12:18
• Thanks @UlrichNeumann, just changed them. Habit crossover from using LaTeX. Nov 27, 2023 at 12:25

I suspect that the issue is that in your code, Mathematica is reevaluating Integrate[f[s] (E^(-I n s)), {s, -Pi, Pi}] for every summand in every frame — which amounts to a couple of thousand calls to Integrate. It is much more efficient to get the Fourier coefficients in general closed form and then ask Mathematica to plot the functions:

(* preceding code as before *)

k = {-2 Pi, -Pi, 0, Pi, 2 Pi}

a[n_] = Piecewise[{{Integrate[f[s] (E^(-I n s)), {s, -Pi, Pi}],
n != 0}, {Integrate[f[s], {s, -Pi, Pi}], n == 0}}]

plot[m_] := Plot[(1/(2 Pi)) Sum[E^(I x n) a[n], {n, -m, m}], {x, -2 Pi, 2 Pi},
(* ... remaining code as before *)


Note that the Piecewise in the definition of a[n] is needed because the general form for a[n] is indeterminate when $$n = 0$$.

Modified thus, the code takes a minute or two to evaluate but eventually exports a sequence of 60 PNG files, each one containing a frame of the animation. (Whether or not this is the intended output is another question, but at least it doesn't crash now.)

• You, sir, are an angel. Thank you for alleviating my suffering @MichaelSeifert. It just so happens this was not my intended output as I need to now figure out how to get one frame for each value of N, but that's my problem and you've helped me with the worst. All the best and thanks again for the learning moment! Nov 27, 2023 at 14:41