Off-On Fourier Series

I have been fascinated lately with the concept of frequency spectrum and the idea that all periodic signals can be approximated by an infinite sum of sinusoidal functions. There are many introductory videos on this subject, usually titled as introductions to the Fourier transform.

As far as the actual math involved, this YouTube* video was very helpful:
Compute Fourier Series Representation of a Function

He converts an off-on type of function to a fourier series. After the integration, we get this:

I translated that into some plots in Racket, to give the visual idea. Say we only add in a single sinusoid:

Then, another:

And a few more:

And a lot more:

And finally, hundreds of them:

It cannot quite perfectly represent the function, because the Fourier series adds an extra point in between the switch from off to on (and back), whereas the original just jumps from 0 to 1 (and back).

Here is the Racket code for those interested (I did not bother to optimize):

``````#lang racket

(require plot)

(define (pulse x l)
(letrec ([pulse_
(lambda (acc n)
(if (> n l) acc
(pulse_
(+ acc
(/ (* 2
(sin (* (+ (* 2 n) 1) pi x)))
(* (+ (* 2 n) 1) pi)))
(+ n 1))))])
(pulse_ 0.5 0)))

(define (pulseplot l)
(plot
(function (lambda (x) (pulse x l)) -1 3)))``````