;; cell/id: intro ;; # Building a square wave out of sine waves ;; ;; A square wave jumps between $-1$ and $+1$ every half turn. It looks ;; like the least sine-like curve there is, yet Fourier showed it is a ;; sum of sines. The sum is infinite, and it uses only the **odd** ;; harmonics: ;; ;; $$f(x) = \frac{4}{\pi}\left(\sin x + \frac{\sin 3x}{3} + \frac{\sin 5x}{5} + \cdots\right) = \frac{4}{\pi}\sum_{k=1}^{\infty} \frac{\sin\big((2k-1)x\big)}{2k-1}$$ ;; ;; Run the cells top to bottom with **Eval**, then drag things around. ^{:cell/id "square"} (defn square "The square wave itself: +1 on (0, π), -1 on (π, 2π), repeating." [x] (if (neg? (js/Math.sin x)) -1 1)) ^{:cell/id "partial-sum"} (defn partial-sum "The first n terms of the series: S_n(x) = 4/π · Σ sin((2k-1)x)/(2k-1)." [n x] (* (/ 4 js/Math.PI) (reduce + (for [k (range 1 (inc n)) :let [h (dec (* 2 k))]] (/ (js/Math.sin (* h x)) h))))) ;; cell/id: coefficients-explainer ;; ## Where the coefficients come from ;; ;; Each coefficient measures how much of $\sin(kx)$ the wave contains, ;; by averaging their product over one period: ;; ;; $$b_k = \frac{1}{\pi}\int_{-\pi}^{\pi} f(x)\sin(kx)\ dx$$ ;; ;; The wave and every sine are odd functions, so their product is even ;; and the integral is twice the one over $(0, \pi)$, where the wave is ;; just $1$: ;; ;; $$b_k = \frac{2}{\pi}\int_{0}^{\pi} \sin(kx)\ dx = \frac{2}{\pi k}\big(1 - \cos(k\pi)\big)$$ ;; ;; That is $\frac{4}{\pi k}$ for odd $k$ and $0$ for even $k$: over a ;; period, $\sin(2x)$ spends as much time agreeing with the square wave ;; as disagreeing. The next cell checks it numerically, with Emmy's ;; integrator, against the formula. ^{:cell/id "coefficients"} (for [k (range 1 8)] {:k k :numeric (* (/ 2 js/Math.PI) (emmy.env/definite-integral (fn [x] (js/Math.sin (* k x))) 0 js/Math.PI)) :formula (if (odd? k) (/ 4 (* js/Math.PI k)) 0)}) ;; cell/id: symbolic-explainer ;; ## The partial sum, as algebra ;; ;; Emmy can build the same sum symbolically. A cell that evaluates to a ;; symbolic expression is typeset as maths, so here are the first four ;; terms written out by the computer rather than by hand: ^{:cell/id "symbolic"} (let [x 'x] (reduce emmy.env/+ (for [k (range 1 5) :let [h (dec (* 2 k))]] (emmy.env/* (emmy.env// 4 (emmy.env/* h 'pi)) (emmy.env/sin (emmy.env/* h x)))))) ;; cell/id: interactive-explainer ;; ## Add terms yourself ;; ;; The white curve is the partial sum $S_N(x)$; the faint one is the ;; square wave. **Drag the pink point** left or right to change $N$, the ;; number of terms: $N$ is its $x$ coordinate, rounded (its height ;; doesn't matter). ;; ;; As $N$ grows the sum hugs the square wave ever more tightly, except ;; right beside each jump. There it always overshoots by about 9% of ;; the jump, however many terms you add; the overshoot just gets ;; narrower. That stubborn spike is the **Gibbs phenomenon**: its ;; height tends to ;; ;; $$\frac{2}{\pi}\int_0^{\pi}\frac{\sin t}{t}\ dt \approx 1.1790$$ ;; ;; times the wave's amplitude, not to 1. ^{:cell/id "n-state"} (def !n ;; The draggable point's position; its x coordinate, rounded, is N. (reagent.core/atom [5 -1.6])) ^{:cell/id "terms"} (defn terms "N from the point's x position: at least 1, at most 60." [[x _]] (max 1 (min 60 (js/Math.round x)))) ^{:cell/id "square-wave-points"} (def square-wave-points ;; The square wave drawn as a polyline, with vertical edges at each jump. (vec (mapcat (fn [j] (let [x0 (* j js/Math.PI) y (if (even? j) 1 -1)] [[x0 y] [(+ x0 js/Math.PI) y]])) (range -3 3)))) ^{:cell/id "interactive"} ['mafs.core/Mafs {:height 420 :view-box {:x [-7 7] :y [-2 2]}} ['mafs.coordinates/Cartesian {}] ['mafs.core/Polyline {:points square-wave-points :color "#888" :stroke-opacity 0.5}] [(fn [] (let [n (terms @!n)] [:<> [mafs.plot/OfX {:y #(partial-sum n %) :color "white"}] [mafs.core/Text {:x 0.3 :y 1.75 :attach "e" :size 18} (str "N = " n)] [mafs.core/Text {:x 0.3 :y 1.45 :attach "e" :size 14 :color "#aaa"} (str "peak ≈ " (.toFixed (partial-sum n (/ js/Math.PI (* 2 n))) 4))]]))] ['mafs.core/MovablePoint {:atom !n :color "#ff4fa3"}]] ;; cell/id: epicycles-explainer ;; ## Circles on circles ;; ;; Each term $\frac{4}{\pi k}\sin(kx)$ is the height of a point going ;; round a circle of radius $\frac{4}{\pi k}$ at $k$ times the speed of ;; the first. Stack the circles, each centred on the tip of the one ;; before, and the height of the last tip *is* the partial sum. Traced ;; out to the right over time, it draws the square wave. Here are the ;; first five; change `epicycle-terms` and re-evaluate the cells below ;; it to stack more. ^{:cell/id "epicycle-terms"} (def epicycle-terms 5) ^{:cell/id "epicycles"} (defn epicycles "The scene at angle t: the circles, the chain of radii, and the trace." [t] (let [harmonics (map #(dec (* 2 %)) (range 1 (inc epicycle-terms))) origin [-3.5 0] ;; The tips of the chain, starting at the origin. tips (reductions (fn [[x y] h] (let [r (/ 4 (* js/Math.PI h))] [(+ x (* r (js/Math.cos (* h t)))) (+ y (* r (js/Math.sin (* h t))))])) origin harmonics) [_ tip-y] (last tips) trace-x0 0 ;; The last tip's height for the past full turn, newest at the left. trace (for [i (range 0 201) :let [s (- t (* i (/ (* 2 js/Math.PI) 200)))]] [(+ trace-x0 (* i (/ 6 200))) (partial-sum epicycle-terms s)])] (into ['mafs.core/Mafs {:height 360 :view-box {:x [-6 6.5] :y [-2 2]}} ['mafs.coordinates/Cartesian {:x-axis false :y-axis false}]] (concat (for [[c h] (map vector tips harmonics)] ['mafs.core/Circle {:center c :radius (/ 4 (* js/Math.PI h)) :color "#888" :fill-opacity 0 :stroke-opacity 0.4}]) [['mafs.core/Polyline {:points (vec tips) :color "#ff4fa3"}] ['mafs.core/Polyline {:points [(last tips) [trace-x0 tip-y]] :color "#aaa" :stroke-opacity 0.5}] ['mafs.core/Polyline {:points (vec trace) :color "white"}] ['mafs.core/Point {:x trace-x0 :y tip-y :color "#ff4fa3"}]])))) ^{:cell/id "animate"} (fn [frac] (epicycles (* frac 2 js/Math.PI)))