Learning Scientific Programming with Python (2nd edition)
P6.7.2: Fourier expansion of a square wave
Question P6.7.2
A square wave of period $T$ may be defined through the following function: $$ f_\mathrm{sq}(t) = \left\{ \begin{array}{ll} 1 & t < T/2 \\ -1 & t \ge T/2 \end{array} \right. $$ with $f(t) = f(t + nT)$ for $n=\pm 1, \pm 2, \cdots$.
Plot the square wave with $T=1$ (and hence cycle frequency, $\nu=1$) for $0 \le t < 2$ taking a grid of 2048 time points over this interval. Calculate and plot its discrete Fourier Transform.
The Fourier expansion of this function is the infinite series $$ f_\mathrm{sq}(t) = \frac{4}{\pi} \sum_{k=1}^{\infty} \frac{1}{2k-1}\sin[2\pi(2k-1)\nu t] $$ Compare the square wave function with this Fourier expansion truncated at 3, 9 and 18 terms. Also compare their (suitably normalized) Fourier transforms: the missing frequencies in each truncated series should appear as zeros in its Fourier transform, whereas the present terms will have intensities $4/[\pi(2k-1)]$.