Square Waves Decomposition of a Sine Wave

I’ve been on Freenode’s #math channel the other day when someone logged in and asked if and how a sine wave can be decomposed into a series of square waves (with integral frequencies). I wrote the following programs to investigate this.

They use a greedy algorithm, that tries each frequency and then finds the amplitude of the corresponding wave that reduces the energy of the total wave by as much as possible.

There’s what seems to be a more analytic method of doing the Sine-into-Square-Waves decomposition. (There’s also more about it).


The C version is faster, but both produce identical results. The Perl version requires PDL - the Perl Data Language.