<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Fourier Transform &#8211; BetterExplained</title>
	<atom:link href="https://betterexplained.com/topics/fourier-transform/feed/" rel="self" type="application/rss+xml" />
	<link>https://betterexplained.com</link>
	<description>Math lessons that click</description>
	<lastBuildDate>Mon, 08 Dec 2025 22:27:03 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	
	<item>
		<title>Intuitive Guide to Convolution</title>
		<link>https://betterexplained.com/articles/intuitive-convolution/</link>
					<comments>https://betterexplained.com/articles/intuitive-convolution/#disqus_thread</comments>
		
		<dc:creator><![CDATA[kalid]]></dc:creator>
		<pubDate>Mon, 23 Nov 2020 19:08:46 +0000</pubDate>
				<category><![CDATA[Calculus]]></category>
				<category><![CDATA[Convolution]]></category>
				<category><![CDATA[Fourier Transform]]></category>
		<guid isPermaLink="false">https://betterexplained.com/?p=12383</guid>

					<description><![CDATA[Like making engineering students squirm? Have them explain convolution and (if you're barbarous) the convolution theorem. They'll mutter something about sliding windows as they try to escape through one. Convolution is usually introduced with its formal definition: Yikes. Let's start without calculus: Convolution is fancy multiplication. Part 1: Hospital Analogy Imagine you manage a hospital [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Like making engineering students squirm? Have them explain convolution and (if you're barbarous) the convolution theorem. They'll mutter something about sliding windows as they try to escape through one.</p>

<p>Convolution is usually introduced with its formal definition:</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/3b38c59c70f4d4c69bbc5d81c2fd0d91.png' width='250' height='43' alt='\displaystyle{ (f * g )(t) = \int_{-\infty}^\infty f(\tau) g(t - \tau) d\tau }' class='tex'></p>

<p>Yikes. Let's start <em>without</em> calculus: <strong>Convolution is fancy multiplication.</strong></p>
</p>

<h2><span id="Part_1_Hospital_Analogy">Part 1: Hospital Analogy</span></h2>

<p>Imagine you manage a hospital treating patients with a single disease. You have:</p>

<ul>
<li><strong>A treatment plan:</strong> <code>[3]</code> Every patient gets 3 units of the cure on their first day.</li>
<li><strong>A list of patients:</strong> <code>[1 2 3 4 5]</code> Your patient count for the week (1 person Monday, 2 people on Tuesday, etc.).</li>
</ul>

<p>Question: How much medicine do you use each day? Well, that's just a quick multiplication:</p>

<pre><code>Plan  *  Patients       = Daily Usage
[3]   *  [1 2 3 4 5]    = [3 6 9 12 15]
</code></pre>

<p>Multiplying the plan by the patient list gives the usage for the upcoming days: <code>[3 6 9 12 15]</code>. Everyday multiplication (<code>3 x 4</code>) means using the plan with a single day of patients: <code>[3] * [4] = [12]</code>.</p>

<h3><span id="Intuition_For_Convolution">Intuition For Convolution</span></h3>

<p>Let's say the disease mutates and requires a multi-day treatment. You create a new plan: <code>Plan: [3 2 1]</code></p>

<p>That means 3 units of the cure on the first day, 2 on the second, and 1 on the third. Ok. Given the same patient schedule  <code>[1 2 3 4 5]</code>, what's our medicine usage each day?</p>

<p>Uh... shoot. It's not a quick multiplication:</p>

<ul>
<li>On Monday, 1 patient comes in. It's her first day, so she gets 3 units.</li>
<li>On Tuesday, the Monday gal gets 2 units (her second day), but two new patients arrive, who get 3 each (2 * 3 = 6). The total is 2 + (2 * 3) = 8 units.</li>
<li>On Wednesday, it's trickier: The Monday gal finishes (1 unit, her last day), the Tuesday people get 2 units (2 * 2), and there are 3 new Wednesday people... argh.</li>
</ul>

<p>The patients are overlapping and it's hard to track. How can we organize this calculation?</p>

<p>An idea: imagine <em>flipping</em> the patient list, so the first patient is on the right:</p>

<pre><code>           Start of line
 5 4 3 2 1
</code></pre>

<p>Next, imagine we have 3 separate rooms where we apply the proper dose:</p>

<pre><code> Rooms     3 2 1              
</code></pre>

<p>On your first day, you walk into the first room and get 3 units of medicine. The next day, you walk into room #2 and get 2 units. On the last day, you walk into room #3 and get 1 unit. There's no rooms afterwards, and your treatment is done.</p>

<p>To calculate the total medicine usage, line up the patients and walk them through the rooms:</p>

<pre><code> Monday
 ----------------------------
 Rooms                  3 2 1                                      
 Patients       5 4 3 2 1

 Usage                  3
</code></pre>

<p>On Monday (our first day), we have a single patient in the first room. She gets 3 units, for a total usage of 3. Makes sense, right?</p>

<p>On Tuesday, everyone takes a step forward:</p>

<pre><code> Tuesday
 ----------------------------
 Rooms                  3 2 1              
 Patients -&gt;      5 4 3 2 1

 Usage                  6 2      = 8
</code></pre>

<p>The first patient is now in the second room, and there's 2 new patients in the first room. We multiply each room's dose by the patient count, then combine.</p>

<p>Every day we just walk the list forward:</p>

<pre><code> Wednesday
 ----------------------------
 Rooms                  3 2 1              
 Patients -&gt;        5 4 3 2 1

 Usage                  9 4 1    = 14


 Thursday
 -----------------------------
 Rooms                  3 2 1              
 Patients -&gt;          5 4 3 2 1

 Usage                 12 6 2    = 20


 Friday
 -----------------------------
 Rooms                  3 2 1              
 Patients -&gt;            5 4 3 2 1

 Usage                 15 8 3    = 26
</code></pre>

<p>Whoa! It's intricate, but we figured it out, right? We can find the usage for any day by reversing the list, sliding it to the desired day, and combining the doses.</p>

<p>The total day-by-day usage looks like this (don't forget Sat and Sun, since some patients began on Friday):</p>

<pre><code>Plan      *  Patient List   = Total Daily Usage

[3 2 1]   *  [1 2 3 4 5]    = [3 8 14 20 26 14 5]
              M T W T F        M T W  T  F  S  S
</code></pre>

<p>This calculation is the <em>convolution</em> of the plan and patient list. It's a fancy multiplication between a list of input numbers and a "program".</p>

<h3><span id="Interactive_Demo">Interactive Demo</span></h3>

<p>Here's a <a href="https://www.desmos.com/calculator/uxtsoxmppq">live demo</a>. Try changing <code>F</code> (the plan) or <code>G</code> (the patient list). The convolution <img src="https://betterexplained.com/latex/5b8b0db110679d1177f3.png" alt="$c(t)$" width="29" height="19" style="vertical-align:-4.53px" class="bex-math"></img> matches our manual calculation above.</p>

<iframe src="https://www.desmos.com/calculator/lrcayuc5te" width="100%" height="700px" style="left: 0%; max-width: 100vw; position: relative; width: 100vw; max-width: 900px;" frameborder=0></iframe>

<p>(We define functions <img src="https://betterexplained.com/latex/146ef99c55cfa5dede83.png" alt="$f(x)$" width="35" height="19" style="vertical-align:-4.53px" class="bex-math"></img> and <img src="https://betterexplained.com/latex/67db49cba7a7b09a6950.png" alt="$g(x)$" width="34" height="19" style="vertical-align:-4.53px" class="bex-math"></img> to pad each list with zero, and adjust for the list index starting at 1.)</p>

<p>You can do a quick convolution with <a href="https://www.wolframalpha.com/input/?i=ListConvolve%5B%7B3%2C+2%2C+1%7D%2C+%7B1%2C+2%2C+3%2C+4%2C+5%7D%2C+%7B1%2C+-1%7D%2C+0%5D+">Wolfram Alpha</a>:</p>

<pre><code>ListConvolve[{3, 2, 1}, {1, 2, 3, 4, 5}, {1, -1}, 0]
{3, 8, 14, 20, 26, 14, 5}
</code></pre>

<p>(The extra <code>{1, -1}, 0</code> aligns the lists and pads with zero.)</p>

<h3><span id="Application_COVID_Ventilator_Usage">Application: COVID Ventilator Usage</span></h3>

<p>I started this article 5 years ago (intuition takes a while...), but unfortunately the analogy is relevant today.</p>

<p>Let's use convolution to estimate ventilator usage for incoming patients.</p>

<ul>
<li>Set <img src="https://betterexplained.com/latex/146ef99c55cfa5dede83.png" alt="$f(x)$" width="35" height="19" style="vertical-align:-4.53px" class="bex-math"></img> as the percent of patients needing ventilators. For example, <code>[.05 .03 .01]</code> means 5% of patients need ventilators the first week, 3% the second week, and 1% the third week.</li>
<li>Set <img src="https://betterexplained.com/latex/67db49cba7a7b09a6950.png" alt="$g(x)$" width="34" height="19" style="vertical-align:-4.53px" class="bex-math"></img> as the weekly incoming patients, in thousands.</li>
<li>The convolution <img src="https://betterexplained.com/latex/3caf58f7c352a8c0e542.png" alt="$c(t) = f * g$" width="89" height="19" style="vertical-align:-4.53px" class="bex-math"></img>, shows how many ventilators are needed each week (in thousands). <img src="https://betterexplained.com/latex/7929c9805f7d2b4a4997.png" alt="$c(5)$" width="31" height="19" style="vertical-align:-4.53px" class="bex-math"></img> is how many ventilators are needed 5 weeks from now.</li>
</ul>

<p>Let's try it out:</p>

<ul>
<li><code>F = [.05, .03, .01]</code> is the ventilator use percentage by week</li>
<li><code>G = [10, 20, 30, 20, 10, 10, 10]</code>, is the incoming hospitalized patients. It starts at 10k per week, rises to 30k, then decays to 10k.</li>
</ul>

<p>With these numbers, we expect a max ventilator use of 2.2k in 2 weeks:</p>

<p><img decoding="async" src="https://betterexplained.com/wp-content/uploads/convolution/Convolution_Demo-covid.png" alt="Convolution_Demo" class="webpexpress-processed"></p>

<p>The convolution drops to 0 after 9 weeks because the patient list has run out. In this example, we're interested in the peak value the convolution hits, not the long-term total.</p>

<p>Other plans to convolve may be drug doses, vaccine appointments (one today, another a month from now), reinfections, and other complex interactions.</p>

<p>The hospital analogy is the mental model I wish I had when learning. Now that we've tried it with actual numbers, let's add the Math Juice and convert the analogy to calculus.</p>

<h2><span id="Part_2_The_Calculus_Definition">Part 2: The Calculus Definition</span></h2>

<p>So, what happened in our example? We had a list of patients and a plan. If the plan were simple (single day <code>[3]</code>), regular multiplication would have worked. Because the plan was complex, we had to "convolve" it.</p>

<p>Time for some Fun Facts&#x2122;:</p>

<ul>
<li><p>Convolution is written <img src="https://betterexplained.com/latex/39d7d2e7d2ebe3ce2ebc.png" alt="$f * g$" width="36" height="17" style="vertical-align:-3.71px" class="bex-math"></img>, with an asterisk. Yes, an asterisk usually indicates multiplication, but in advanced calculus class, it indicates a convolution. Regular multiplication is just implied (<img src="https://betterexplained.com/latex/78104d82be8c6a943e1d.png" alt="$fg$" width="19" height="17" style="vertical-align:-3.71px" class="bex-math"></img>).</p></li>
<li><p>The result of a convolution is a new <em>function</em> that gives the total usage for any day ("What was the total usage on day <img src="https://betterexplained.com/latex/472ee22169c1b2c44993.png" alt="$t=3$" width="40" height="14" style="vertical-align:-1.49px" class="bex-math"></img>?"). We can graph the convolution over time to see the day-by-day totals.</p></li>
</ul>

<p>Now the big aha: <strong>Convolution reverses one of the lists!</strong> Here's why.</p>

<p>Let's call our treatment plan <img src="https://betterexplained.com/latex/146ef99c55cfa5dede83.png" alt="$f(x)$" width="35" height="19" style="vertical-align:-4.53px" class="bex-math"></img>. In our example, we used <code>[3 2 1]</code>.</p>

<p>The list of patients (inputs) is <img src="https://betterexplained.com/latex/67db49cba7a7b09a6950.png" alt="$g(x)$" width="34" height="19" style="vertical-align:-4.53px" class="bex-math"></img>. However, we need to <em>reverse</em> this list as we slide it, so the earliest patient (Monday) enters the hospital first (first in, first out). This means we need to use <img src="https://betterexplained.com/latex/941c6d33136c5abf3e97.png" alt="$g(-x)$" width="48" height="19" style="vertical-align:-4.53px" class="bex-math"></img>, the horizontal reflection of <img src="https://betterexplained.com/latex/67db49cba7a7b09a6950.png" alt="$g(x)$" width="34" height="19" style="vertical-align:-4.53px" class="bex-math"></img>. <code>[1 2 3 4 5]</code> becomes <code>[5 4 3 2 1]</code>.</p>

<p>Now that we have the reversed list, pick a day to compute (<img src="https://betterexplained.com/latex/ab09c71153409a08a2f8.png" alt="$t = 0, 1, 2...$" width="93" height="16" style="vertical-align:-3.51px" class="bex-math"></img>). To slide our patient list by this much, we use: <img src="https://betterexplained.com/latex/44ae1d72b35c47571302.png" alt="$g(-x + t)$" width="76" height="19" style="vertical-align:-4.53px" class="bex-math"></img>. That is, we reverse the list (<img src="https://betterexplained.com/latex/65120d102a8a3f5d1adf.png" alt="$-x$" width="25" height="13" style="vertical-align:-1.49px" class="bex-math"></img>) and jump to the correct day (<img src="https://betterexplained.com/latex/0e1f959a5ad0480273f7.png" alt="$+t$" width="21" height="13" style="vertical-align:-1.49px" class="bex-math"></img>).</p>

<p>We have our scenario:</p>

<ul>
<li><img src="https://betterexplained.com/latex/146ef99c55cfa5dede83.png" alt="$f(x)$" width="35" height="19" style="vertical-align:-4.53px" class="bex-math"></img> is the plan to use</li>
<li><img src="https://betterexplained.com/latex/44ae1d72b35c47571302.png" alt="$g(-x + t)$" width="76" height="19" style="vertical-align:-4.53px" class="bex-math"></img> is the list of inputs (flipped and slid to the right day).</li>
</ul>

<p>To get the total usage on day <img src="https://betterexplained.com/latex/2de0691d41e87626a221.png" alt="$t$" width="7" height="12" style="vertical-align:-0.2px" class="bex-math"></img>, we multiply each patient with the plan, and sum the results (an integral). To account for any possible length, we go from -infinity to +infinity.</p>

<p>Now we can describe convolution formally using calculus:</p>

<p><img decoding="async" src="https://betterexplained.com/ColorizedMath/img/Convolution.png" alt="convolution" /></p>

<p>(Like <a href="https://betterexplained.com/articles/colorized-math-equations/">colorized math</a>? There's more.)</p>

<p>Phew! That's quite few symbols. Some notes:</p>

<ul>
<li>We use a dummy variable <img src="https://betterexplained.com/latex/9656236114bc9ec97310.png" alt="$\tau$" width="10" height="9" style="vertical-align:-0.23px" class="bex-math"></img> (tau) for the intermediate computation. Imagine <img src="https://betterexplained.com/latex/9656236114bc9ec97310.png" alt="$\tau$" width="10" height="9" style="vertical-align:-0.23px" class="bex-math"></img> as knocking on each room (<img src="https://betterexplained.com/latex/93452d264f283579cb30.png" alt="$\tau={0, 1, 2, 3...}$" width="112" height="16" style="vertical-align:-3.51px" class="bex-math"></img>), finding the dosage [<img src="https://betterexplained.com/latex/6c6f71d18fe4039ac62b.png" alt="$f(\tau)$" width="34" height="19" style="vertical-align:-4.53px" class="bex-math"></img>], the number of patients [<img src="https://betterexplained.com/latex/af93a706afe6f590c1af.png" alt="$g(t - \tau)$" width="61" height="19" style="vertical-align:-4.53px" class="bex-math"></img>], multiplying them, and totaling things in the integral. Yowza. The so-called "dummy" variable <img src="https://betterexplained.com/latex/9656236114bc9ec97310.png" alt="$\tau$" width="10" height="9" style="vertical-align:-0.23px" class="bex-math"></img> is like <code>i</code> in a <code>for</code> loop: it's temporary, but does the work. (By analogy, <img src="https://betterexplained.com/latex/2de0691d41e87626a221.png" alt="$t$" width="7" height="12" style="vertical-align:-0.2px" class="bex-math"></img> is a global variable has a fixed value during the loop: it's the day we're calculating the usage for, such as <code>t = Day 5</code>).</li>
<li>In the official definition, you'll see <img src="https://betterexplained.com/latex/af93a706afe6f590c1af.png" alt="$g(t - \tau)$" width="61" height="19" style="vertical-align:-4.53px" class="bex-math"></img> instead of <img src="https://betterexplained.com/latex/9e513e47cb178651c036.png" alt="$g(- \tau+ t)$" width="75" height="19" style="vertical-align:-4.53px" class="bex-math"></img>. The second version shows the flip (<img src="https://betterexplained.com/latex/a2f5121e6aefc7695261.png" alt="$-\tau$" width="24" height="13" style="vertical-align:-1.49px" class="bex-math"></img>) and slide (<img src="https://betterexplained.com/latex/0e1f959a5ad0480273f7.png" alt="$+t$" width="21" height="13" style="vertical-align:-1.49px" class="bex-math"></img>). Writing <img src="https://betterexplained.com/latex/af93a706afe6f590c1af.png" alt="$g(t - \tau)$" width="61" height="19" style="vertical-align:-4.53px" class="bex-math"></img> makes it seem like we're interested in the difference between the variables, which confused me.</li>
<li>The treatment plan (program to run) is called the <em>kernel</em>: you convolve a kernel with an input.</li>
</ul>

<p>Not too bad, right? The equation is a formal description of the analogy.</p>

<h2><span id="Part_3_Mathematical_Properties_of_Convolution">Part 3: Mathematical Properties of Convolution</span></h2>

<p>We can't discover a new math operation without taking it for a spin. Let's see how it behaves.</p>

<h3><span id="Convolution_is_commutative_f_g_g_f">Convolution is commutative: f * g = g * f</span></h3>

<p>In our computation, we flipped the patient list and kept the plan the same. Could we have flipped the plan instead?</p>

<p>You bet. Imagine the patients are immobile, and stay in their rooms: <code>[1 2 3 4 5]</code>. To deliver the medicine, we have 3 medical carts that go to each room and deliver the dose. Each day, they slide forward one position.</p>

<pre><code>  Carts -&gt;
  1 2 3

      1 2 3 4 5
      Patients
</code></pre>

<p>As before, though our plan is written <code>[3 2 1]</code> (3 units on the first day), we flip the order of the carts to<code>[1 2 3]</code>. That way, a patient gets 3 units on their first day, as we expect. Checking with Wolfram Alpha, the <a href="https://www.wolframalpha.com/input/?i=ListConvolve%5B%7B1%2C+2%2C+3%2C+4%2C+5%7D%2C+%7B3%2C+2%2C+1%7D%2C+%7B1%2C+-1%7D%2C+0%5D+">calculation</a> is the same.</p>

<pre><code>ListConvolve[{1, 2, 3, 4, 5}, {3, 2, 1}, {1, -1}, 0]
{3, 8, 14, 20, 26, 14, 5}
</code></pre>

<p>Cool! It looks like convolution is commutative:</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/e16bac899ff20ecdadbab51b60c37d3b.png' width='97' height='17' alt='\displaystyle{f * g = g * f}' class='tex'></p>

<p>and we can decide to flip either <img src="https://betterexplained.com/latex/220f6de5269f95327e46.png" alt="$f$" width="10" height="17" style="vertical-align:-3.71px" class="bex-math"></img> or <img src="https://betterexplained.com/latex/e1527dc2bb80433e9e49.png" alt="$g$" width="9" height="12" style="vertical-align:-3.71px" class="bex-math"></img> when calculating the integral. Surprising, right?</p>

<h3><span id="The_integral_of_the_convolution">The integral of the convolution</span></h3>

<p>When all treatments are finished, what was the <em>total</em> medicine usage? This is the <strong>integral of the convolution</strong>. (A few minutes ago, that phrase would have you jumping out of a window.)</p>

<p>But it's a simple calculation. Our plan gives each patient <code>sum([3 2 1]) = 6</code> units of medicine. And we have <code>sum([1 2 3 4 5]) = 15</code> patients. The total usage is just <code>6 x 15 = 90</code> units.</p>

<p>Wow, that was easy: the usage for the <em>entire</em> convolution is just the product of the subtotals!</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/56e822f91d16dfbb8f13a0a8d52d0b46.png' width='168' height='41' alt='\displaystyle{\int (f * g) = \int f \cdot \int g }' class='tex'></p>

<p>I hope this clicks intuitively. Note that this trick works for convolution, but not integrals in general. For example:</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/78f2d953a7a319e8866bcc10aa892a79.png' width='165' height='41' alt='\displaystyle{ \int (x \cdot x) \ne \int x \cdot \int x }' class='tex'></p>

<p>If we separate <img src="https://betterexplained.com/latex/9ebea033313303badad3.png" alt="$x \cdot x$" width="34" height="9" style="vertical-align:-0.2px" class="bex-math"></img> into two integrals we get:</p>

<ul>
<li><img src="https://betterexplained.com/latex/445126f31274e60f8c89.png" alt="$\int (x \cdot x) = \int x^2 = \frac{1}{3} x^3$" width="173" height="23" style="vertical-align:-6.53px" class="bex-math"></img></li>
<li><img src="https://betterexplained.com/latex/f0fa88310b5d3573ae0f.png" alt="$\int x \cdot \int x = \frac{1}{2}x^2 \cdot \frac{1}{2}x^2 = \frac{1}{4}x^4$" width="222" height="22" style="vertical-align:-6.25px" class="bex-math"></img></li>
</ul>

<p>and those aren't the same. (Calculus would be much easier if we could split integrals like this.) It's strange, but <img src="https://betterexplained.com/latex/4ae6f081a1614aa4c82f.png" alt="$\int (f * g)$" width="61" height="21" style="vertical-align:-5.53px" class="bex-math"></img> is probably easier to solve than <img src="https://betterexplained.com/latex/c7956480841fd47d6358.png" alt="$\int (fg)$" width="44" height="21" style="vertical-align:-5.53px" class="bex-math"></img>.</p>

<h3><span id="Impulse_Response">Impulse Response</span></h3>

<p>What happens if we sent a single patient through the hospital? The convolution would just be that day's plan.</p>

<pre><code>Plan    * Patients = Convolution
[3 2 1] * [1]      = [3 2 1]
</code></pre>

<p>In other words, convolving with <code>[1]</code> gives us the original plan.</p>

<p>In calculus terms, a spike of <code>[1]</code> (and 0 otherwise) is the <a href="https://en.wikipedia.org/wiki/Dirac_delta_function">Dirac Delta Function</a>. In terms of convolutions, this function acts like the number 1 and returns the original function:</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/b29d7fb1b5d01e09a53c6559aa4b95a8.png' width='132' height='19' alt='\displaystyle{f(t) * \delta(t) = f(t)}' class='tex'></p>

<p>We can delay the delta function by T, which delays the resulting convolution function too. Imagine our single patient shows up a week late (<img src="https://betterexplained.com/latex/09d266a2482413c04031.png" alt="$\delta(t - T)$" width="64" height="19" style="vertical-align:-4.53px" class="bex-math"></img>), so our medicine usage gets delayed for a week too:</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/1507a724e304125262fce84ee01f209c.png' width='202' height='19' alt='\displaystyle{f(t) * \delta(t - T) = f(t - T)}' class='tex'></p>

<h2><span id="Part_4_Convolution_Theorem_The_Fourier_Transform">Part 4: Convolution Theorem &amp; The Fourier Transform</span></h2>

<p>The <a href="https://betterexplained.com/articles/an-interactive-guide-to-the-fourier-transform/">Fourier Transform</a> (written with a fancy <img src="https://betterexplained.com/latex/fb3d22404d8f07b8e247.png" alt="$\mathscr{F}$" width="18" height="14" style="vertical-align:-0.65px" class="bex-math"></img>) converts a function <img src="https://betterexplained.com/latex/34867dbe6c2bfca4bf25.png" alt="$f(t)$" width="31" height="19" style="vertical-align:-4.53px" class="bex-math"></img> into a list of cyclical ingredients <img src="https://betterexplained.com/latex/1c5b76a5d6dc15af8a83.png" alt="$F(s)$" width="37" height="19" style="vertical-align:-4.53px" class="bex-math"></img>:</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/8c9ad40ce73b75644d58416c309d966d.png' width='101' height='25' alt='\displaystyle{f(t) \xrightarrow{\mathscr{F}} F(s)}' class='tex'></p>

<p>As an operator, this can be written <img src="https://betterexplained.com/latex/fcae50f315cb63515e43.png" alt="$\mathscr{F}\lbrace f \rbrace = F$" width="84" height="19" style="vertical-align:-4.53px" class="bex-math"></img>.</p>

<p>In our analogy, we convolved the plan and patient list with a fancy multiplication. Since the Fourier Transform gives us lists of ingredients, could we get the same result by mixing the <em>ingredient lists</em>?</p>

<p>Yep, we can: <strong>Fancy multiplication in the regular world is <em>regular</em> multiplication in the fancy world.</strong></p>

<p>In math terms, "Convolution in the time domain is multiplication in the frequency (Fourier) domain."</p>

<p>Mathematically, this is written:</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/975d50cac9c5ad016dec8d02a36d609c.png' width='99' height='25' alt='\displaystyle{f * g \xrightarrow{\mathscr{F}} FG}' class='tex'></p>

<p>or</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/9de81fb69762e5905e57bfe66b54bdf8.png' width='126' height='19' alt='\displaystyle{\mathscr{F}\lbrace f * g \rbrace = FG}' class='tex'></p>

<p>where <img src="https://betterexplained.com/latex/146ef99c55cfa5dede83.png" alt="$f(x)$" width="35" height="19" style="vertical-align:-4.53px" class="bex-math"></img> and <img src="https://betterexplained.com/latex/67db49cba7a7b09a6950.png" alt="$g(x)$" width="34" height="19" style="vertical-align:-4.53px" class="bex-math"></img> are functions to convolve, with transforms <img src="https://betterexplained.com/latex/1c5b76a5d6dc15af8a83.png" alt="$F(s)$" width="37" height="19" style="vertical-align:-4.53px" class="bex-math"></img> and <img src="https://betterexplained.com/latex/bf0c3c97a503725c8c7a.png" alt="$G(s)$" width="37" height="19" style="vertical-align:-4.53px" class="bex-math"></img>.</p>

<p>We can <a href="https://www-structmed.cimr.cam.ac.uk/Course/Convolution/convolution.html">prove this theorem</a> with advanced calculus, that uses theorems I don't quite understand, but let's think through the meaning.</p>

<p>Because <img src="https://betterexplained.com/latex/1c5b76a5d6dc15af8a83.png" alt="$F(s)$" width="37" height="19" style="vertical-align:-4.53px" class="bex-math"></img> is the Fourier Transform of <img src="https://betterexplained.com/latex/34867dbe6c2bfca4bf25.png" alt="$f(t)$" width="31" height="19" style="vertical-align:-4.53px" class="bex-math"></img>, we can ask for a specific frequency (<img src="https://betterexplained.com/latex/f81f1ef00f8f2705acee.png" alt="$s = 2\text{Hz}$" width="64" height="14" style="vertical-align:-1.49px" class="bex-math"></img>) and get the <em>combined interaction</em> of every data point with that frequency. Let's suppose:</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/0884a3f9a6e39cfddf47bc84424a6d89.png' width='98' height='19' alt='\displaystyle{F(2) = 3 + i}' class='tex'></p>

<p>That means after every data point has been multiplied against the 2Hz cycle, the result is <img src="https://betterexplained.com/latex/7e9a92304539e47e0804.png" alt="$3 + i$" width="38" height="14" style="vertical-align:-1.49px" class="bex-math"></img>. But we could have kept each interaction separate:</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/23d27254660014f82e5c40701fc59a5e.png' width='303' height='19' alt='\displaystyle{F(2) = 3 + i = c_0 + c_1 + c_2 + c_3 ... + c_t}' class='tex'></p>

<p>Where <img src="https://betterexplained.com/latex/7347763bda3d70cefa8d.png" alt="$c_t$" width="14" height="11" style="vertical-align:-2.86px" class="bex-math"></img> is the contribution to the 2Hz frequency from datapoint <img src="https://betterexplained.com/latex/2de0691d41e87626a221.png" alt="$t$" width="7" height="12" style="vertical-align:-0.2px" class="bex-math"></img>. Similarly, we can expand <img src="https://betterexplained.com/latex/bf0c3c97a503725c8c7a.png" alt="$G(s)$" width="37" height="19" style="vertical-align:-4.53px" class="bex-math"></img> into a list of interactions with the 2Hz ingredient. Let's suppose <img src="https://betterexplained.com/latex/349dfb89eb186ffd5c22.png" alt="$G(2) = 7 - i$" width="99" height="19" style="vertical-align:-4.53px" class="bex-math"></img>:</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/173bd83355b2b44e61b86c691e34d49c.png' width='311' height='19' alt='\displaystyle{G(2) = 7 - i = d_0 + d_1 + d_2 + d_3 ... + d_t}' class='tex'></p>

<p>The Convolution Theorem is really saying:</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/e7a16cd19ecb142a8c2905935522697b.png' width='414' height='25' alt='\displaystyle{f * g \xrightarrow{\mathscr{F}} FG = (c_0 + c_1 + c_2 + ...)(d_0 + d_1 + d_2 + ...)}' class='tex'></p>

<p>Our convolution in the regular domain involves a lot of cross-multiplications. In the fancy frequency domain, we <em>still</em> have a bunch of interactions, but <img src="https://betterexplained.com/latex/1c5b76a5d6dc15af8a83.png" alt="$F(s)$" width="37" height="19" style="vertical-align:-4.53px" class="bex-math"></img> and <img src="https://betterexplained.com/latex/bf0c3c97a503725c8c7a.png" alt="$G(s)$" width="37" height="19" style="vertical-align:-4.53px" class="bex-math"></img> have consolidated them. We can just multiply <img src="https://betterexplained.com/latex/3b4ca8388308b95c8475.png" alt="$F(2)G(2) = (3 + i)(7-i)$" width="202" height="19" style="vertical-align:-4.53px" class="bex-math"></img> to find the 2Hz ingredient in the convolved result.</p>

<p>By analogy, suppose you want to calculate:</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/833c92dbdffc2f4600786c0d34386a51.png' width='260' height='19' alt='\displaystyle{(1 + 2 + 3 + 4)(5 + 6 + 7 + 8) = ?}' class='tex'></p>

<p>It's a lot of work to cross-multiply every term: <img src="https://betterexplained.com/latex/62154df5a1faefd85792.png" alt="$(1 \cdot 5) + (1\cdot 6) + (1\cdot 7) + ...$" width="216" height="19" style="vertical-align:-4.53px" class="bex-math"></img></p>

<p>It's better to consolidate the groups into <img src="https://betterexplained.com/latex/4784672072af20446340.png" alt="$(1 + 2 + 3 + 4) = 10$" width="159" height="19" style="vertical-align:-4.53px" class="bex-math"></img> and <img src="https://betterexplained.com/latex/7ffe7bfa68251a457d57.png" alt="$(5 + 6 + 7 + 8) = 26$" width="159" height="19" style="vertical-align:-4.53px" class="bex-math"></img>, and <em>then</em> multiply to get <img src="https://betterexplained.com/latex/4781c3d13ce53560c8c8.png" alt="$10 \cdot 26 = 260$" width="101" height="14" style="vertical-align:-1.49px" class="bex-math"></img>.</p>

<p>This nuance caused me a lot of confusion. It seems like <img src="https://betterexplained.com/latex/9eb0fc49d439ae51f1d0.png" alt="$FG$" width="28" height="14" style="vertical-align:-0.4px" class="bex-math"></img> is a single multiplication, while <img src="https://betterexplained.com/latex/39d7d2e7d2ebe3ce2ebc.png" alt="$f * g$" width="36" height="17" style="vertical-align:-3.71px" class="bex-math"></img> involves a bunch of intermediate terms. I forgot that <img src="https://betterexplained.com/latex/4f57ad0bbe6f740c74fa.png" alt="$F$" width="14" height="13" style="vertical-align:0px" class="bex-math"></img> already did the work of merging a bunch of entries into a single one.</p>

<p>Now, we aren't <em>quite</em> done.</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/b16131bbdcf74439d0327764cc3d3874.png' width='154' height='25' alt='\displaystyle{f * g \xrightarrow{\mathscr{F}} FG \xrightarrow{\mathscr{F^{-1}}} \ ?}' class='tex'></p>

<p>We can convert <img src="https://betterexplained.com/latex/39d7d2e7d2ebe3ce2ebc.png" alt="$f * g$" width="36" height="17" style="vertical-align:-3.71px" class="bex-math"></img> in the time domain into <img src="https://betterexplained.com/latex/9eb0fc49d439ae51f1d0.png" alt="$FG$" width="28" height="14" style="vertical-align:-0.4px" class="bex-math"></img> in the frequency domain, but we probably need it back in the time domain for a usable result:</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/4838206025511ca3236c054e272048a5.png' width='144' height='21' alt='\displaystyle{f * g = \mathscr{F}^{-1} \lbrace FG \rbrace}' class='tex'></p>

<p>You have a riddle in English (<img src="https://betterexplained.com/latex/39d7d2e7d2ebe3ce2ebc.png" alt="$f * g$" width="36" height="17" style="vertical-align:-3.71px" class="bex-math"></img>), you translate it to French (<img src="https://betterexplained.com/latex/9eb0fc49d439ae51f1d0.png" alt="$FG$" width="28" height="14" style="vertical-align:-0.4px" class="bex-math"></img>), get your smart French friend to work out that calculation, then convert it back to English (<img src="https://betterexplained.com/latex/d6d2ad667bd988d616aa.png" alt="$\mathscr{F}^{-1}$" width="37" height="16" style="vertical-align:-0.65px" class="bex-math"></img>).</p>

<h3><span id="And_in_reverse">And in reverse...</span></h3>

<p>The convolution theorem works this way too:</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/c5a0816925f9e3aa674885d90abe00b2.png' width='99' height='25' alt='\displaystyle{fg \xrightarrow{\mathscr{F}} F * G}' class='tex'></p>

<p><strong>Regular multiplication in the regular world is fancy multiplication in the fancy world.</strong></p>

<p>Cool, eh? Instead of multiplying two functions like some cave dweller, put on your monocle, convolve the Fourier Transforms, and convert to the time domain:</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/6869aaa36d056ce64f590d5d92220d83.png' width='144' height='21' alt='\displaystyle{fg = \mathscr{F}^{-1} \lbrace F*G \rbrace}' class='tex'></p>

<p>I'm not saying this is fun, just that it's possible. If your French friend has a gnarly calculation they're struggling with, it might look like arithmetic to you.</p>

<h3><span id="Mini_proof">Mini proof</span></h3>

<p>Remember how we said the integral of a convolution was a multiplication of the individual integrals?</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/56e822f91d16dfbb8f13a0a8d52d0b46.png' width='168' height='41' alt='\displaystyle{\int (f * g) = \int f \cdot \int g }' class='tex'></p>

<p>Well, the Fourier Transform is just a very specific integral, right?</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/502869363dd0f3b4dc8a76053bcbb534.png' width='64' height='41' alt='\displaystyle{\int \rightarrow \mathscr{F}}' class='tex'></p>

<p>So (handwaving), it seems we could swap the general-purpose integral <img src="https://betterexplained.com/latex/a268fc1b5df463b5edf0.png" alt="$\int$" width="12" height="21" style="vertical-align:-5.53px" class="bex-math"></img> for <img src="https://betterexplained.com/latex/fb3d22404d8f07b8e247.png" alt="$\mathscr{F}$" width="18" height="14" style="vertical-align:-0.65px" class="bex-math"></img> and get</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/56b33fef4c78829009660e538336af81.png' width='191' height='19' alt='\displaystyle{\mathscr{F} (f * g) = \mathscr{F} (f) \cdot \mathscr{F} (g) }' class='tex'></p>

<p>which is the convolution theorem. I need a deeper intuition for the <a href="https://math.stackexchange.com/questions/1077990/integral-of-the-convolution-of-two-functions-int-infty-infty-fgxd">proof</a>, but this helps things click.</p>

<h2><span id="Part_5_Applications">Part 5: Applications</span></h2>

<p>The trick with convolution is finding a useful "program" (kernel) to apply to your input. Here's a few examples.</p>

<h3><span id="Moving_averages">Moving averages</span></h3>

<p>Let's say you want a moving average between neighboring items in a list. That is half of each element, added together:</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/4e9c801fbbc424a674e4e466d939a091.png' width='113' height='38' alt='\displaystyle{\frac{a + b}{2} = \frac{a}{2} + \frac{b}{2}}' class='tex'></p>

<p>This is a "multiplication program" of <code>[0.5 0.5]</code> convolved with our list:</p>

<pre><code>ListConvolve[{1, 4, 9, 16, 25}, {0.5, 0.5}, {1, -1}, 0] 
{0.5, 2.5, 6.5, 12.5, 20.5, 12.5}
</code></pre>

<p>We can perform a moving average with a single operation. Neat!</p>

<p>A 3-element moving average would be <code>[.33 .33 .33]</code>, a weighted average could be <code>[.5 .25 .25]</code>.</p>

<h3><span id="Derivatives">Derivatives</span></h3>

<p>The derivative finds the difference between neighboring values. Here's the plan: <code>[1 -1]</code></p>

<pre><code>ListConvolve[{1, 2, 3, 4, 5}, {1, -1}, {1, -1}, 0] 
{1, 1, 1, 1, 1, -5}                         // -5 since we ran out of entries

ListConvolve[{1, 4, 9, 16, 25}, {1, -1}, {1, -1}, 0] 
{1, 3, 5, 7, 9, -25}                        // discrete derivative is 2x + 1
</code></pre>

<p>With a simple kernel, we can find a useful math property on a discrete list. And to get a second derivative, just apply the derivative convolution twice:</p>

<p><code>F * [1 -1] * [1 -1] </code></p>

<p>As a shortcut, we can precompute the final convolutions (<code>[1 -1] * [1 -1]</code> ) and get:</p>

<pre><code>ListConvolve[{1, -1}, {1,-1}, {1, -1}, 0] 
{1, -2, 1}
</code></pre>

<p>Now we have a <em>single</em> kernel <code>[1, -2, 1]</code> that gets the second derivative of a list:</p>

<pre><code>ListConvolve[{1, 4, 9, 16, 25}, {1, -2, 1}, {1, -1}, 0] 
{1, 2, 2, 2, 2, -34, 25}
</code></pre>

<p>Excluding the boundary items, we get the expected second derivative:</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/93d03b535aa28ab5c13b0e3d7ef4dec2.png' width='147' height='23' alt='\displaystyle{x^2 \xrightarrow{d/dx} 2x \xrightarrow{d/dx} 2}' class='tex'></p>

<h3><span id="Blurring_unblurring_images">Blurring / unblurring images</span></h3>

<p>An image blur is essentially a convolution of your image with some "blurring kernel":</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/a133d2923fb791fe5e9bd5474083ada4.png' width='178' height='17' alt='\displaystyle{\text{blurred} = \text{image} * \text{blur}}' class='tex'></p>

<p>The blur of our 2D image requires a <a href="https://en.wikipedia.org/wiki/Kernel_(image_processing)">2D average</a>:</p>

<p><img decoding="async" src="https://betterexplained.com/wp-content/uploads/convolution/convolution-blur-wikipedia.png" alt="Kernel__image_processing__-_Wikipedia" class="webpexpress-processed"></p>

<p>Can we undo the blur? Yep! With our friend the Convolution Theorem, we can do:</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/a133d2923fb791fe5e9bd5474083ada4.png' width='178' height='17' alt='\displaystyle{\text{blurred} = \text{image} * \text{blur}}' class='tex'></p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/1e2717feb61734bf83d7818c909d24a5.png' width='250' height='19' alt='\displaystyle{\mathscr{F} \lbrace \text{blurred} \rbrace = \mathscr{F} \lbrace \text{image} * \text{blur} \rbrace}' class='tex'></p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/45f6a8360051ab4ec3ba8e5af159b539.png' width='270' height='19' alt='\displaystyle{\mathscr{F} \lbrace \text{blurred} \rbrace = \mathscr{F} \lbrace \text{image} \rbrace \mathscr{F} \lbrace \text{blur} \rbrace}' class='tex'></p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/417952a1063203f96d0b0428209b56fd.png' width='203' height='44' alt='\displaystyle{\frac{ \mathscr{F} \lbrace \text{blurred} \rbrace }{\mathscr{F} \lbrace \text{blur} \rbrace} = \mathscr{F} \lbrace \text{image} \rbrace }' class='tex'></p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/ac0a303f5414c3148279e482d396cae1.png' width='224' height='44' alt='\displaystyle{\mathscr{F}^{-1} \lbrace \frac{ \mathscr{F} \lbrace \text{blurred} \rbrace }{\mathscr{F} \lbrace \text{blur} \rbrace} \rbrace = \text{image}}' class='tex'></p>

<p>Whoa! We can recover the original image by dividing out the blur. Convolution is a simple multiplication in the frequency domain, and <em>deconvolution</em> is a simple division in the frequency domain.</p>

<p><img decoding="async" src="https://betterexplained.com/wp-content/uploads/convolution/image-blur.png" alt="image-blur" class="webpexpress-processed"></p>

<p>A short while back, the concept of "deblurring by dividing Fourier Transforms" was gibberish to me. While it can be daunting mathematically, it's getting simpler conceptually.</p>

<p>More reading:</p>

<ul>
<li>Wikipedia on <a href="https://en.wikipedia.org/wiki/Deconvolution">deconvolution</a>,  <a href="https://en.wikipedia.org/wiki/Deblurring">deblurring</a>.</li>
<li><a href="http://www.robots.ox.ac.uk/~az/lectures/ia/lect3.pdf">Image Restoration Lecture</a>, <a href="http://user.engineering.uiowa.edu/~dip/LECTURE/PreProcessing4.html#invconvolution">another one</a>, and <a href="http://fourier.eng.hmc.edu/e161/demos/e161_demo4.html">example for above</a></li>
<li><a href="https://www.mathworks.com/help/images/deblurring-images-using-the-blind-deconvolution-algorithm.html">Blind deconvolution</a> is when you don't know the blur kernel (make a guess)</li>
</ul>

<h3><span id="Algorithm_Trick_Multiplication">Algorithm Trick: Multiplication</span></h3>

<p>What is a number? A list of digits:</p>

<pre><code>1234 = 1000 + 200 + 30 + 4 = [1000 200 30 4]
5678 = 5000 + 600 + 70 + 8 = [5000 600 70 8]
</code></pre>

<p>And what is regular, grade-school multiplication? A digit-by-digit convolution! We sweep one list of digits by the other, multiplying and adding as we go:</p>

<p><img decoding="async" src="https://betterexplained.com/wp-content/uploads/convolution/gradeschoolalgorithm.png" alt="Intuitive Guide to Convolution" class="webpexpress-processed"></p>

<p><a href="https://pythonandr.com/2015/10/13/karatsuba-multiplication-algorithm-python-code/">Source</a></p>

<p>We can perform the calculation by convolving the lists of digits (<a href="https://www.wolframalpha.com/input/?i=ListConvolve%5B%7B1000%2C+200%2C+30%2C+4%7D%2C+%7B8%2C+70%2C+600%2C+5000%7D%2C+%7B1%2C+-1%7D%2C+0%5D">wolfram alpha</a>):</p>

<pre><code>ListConvolve[{1000, 200, 30, 4}, {8, 70, 600, 5000}, {1, -1}, 0]
{8000, 71600, 614240, 5122132, 1018280, 152400, 20000}

sum {8000, 71600, 614240, 5122132, 1018280, 152400, 20000}
7006652
</code></pre>

<p>Note that we pre-flip one of the lists (it gets swapped in the convolution later), and the intermediate calculations are a bit different. But, combining the subtotals gives the expected result.</p>

<h3><span id="Faster_Convolutions">Faster Convolutions</span></h3>

<p>Why convolve instead of doing a regular digit-by-digit multiplication? Well, the convolution theorem lets us substitute convolution with Fourier Transforms:</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/4838206025511ca3236c054e272048a5.png' width='144' height='21' alt='\displaystyle{f * g = \mathscr{F}^{-1} \lbrace FG \rbrace}' class='tex'></p>

<p>The convolution (<img src="https://betterexplained.com/latex/39d7d2e7d2ebe3ce2ebc.png" alt="$f * g$" width="36" height="17" style="vertical-align:-3.71px" class="bex-math"></img>) has complexity <img src="https://betterexplained.com/latex/103277ff874e4c17b58d.png" alt="$O(n^2)$" width="47" height="20" style="vertical-align:-4.53px" class="bex-math"></img>. We have <img src="https://betterexplained.com/latex/e5e0f1078316e19bf059.png" alt="$n$" width="11" height="9" style="vertical-align:-0.2px" class="bex-math"></img> positions to process, with <img src="https://betterexplained.com/latex/e5e0f1078316e19bf059.png" alt="$n$" width="11" height="9" style="vertical-align:-0.2px" class="bex-math"></img> intermediate multiplications at each position.</p>

<p>The right side involves:</p>

<ul>
<li>Two Fourier Transforms, which are normally <img src="https://betterexplained.com/latex/103277ff874e4c17b58d.png" alt="$O(n^2)$" width="47" height="20" style="vertical-align:-4.53px" class="bex-math"></img>. However, the Fast Fourier Transform (a <a href="https://www.youtube.com/watch?v=iTMn0Kt18tg">divide-and-conquer approach</a>) makes them <img src="https://betterexplained.com/latex/a339edf5ab740f9613dc.png" alt="$O(n\log(n))$" width="90" height="19" style="vertical-align:-4.53px" class="bex-math"></img>.</li>
<li>Pointwise multiplication of the final result of the transforms  (<img src="https://betterexplained.com/latex/ca98954286e33e21a66d.png" alt="$\sum a_n \cdot b_n$" width="71" height="19" style="vertical-align:-4.53px" class="bex-math"></img>), which is <img src="https://betterexplained.com/latex/f82fa4d11920dd3253f2.png" alt="$O(n)$" width="39" height="19" style="vertical-align:-4.53px" class="bex-math"></img></li>
<li>An inverse transform, which is <img src="https://betterexplained.com/latex/a339edf5ab740f9613dc.png" alt="$O(n\log(n))$" width="90" height="19" style="vertical-align:-4.53px" class="bex-math"></img></li>
</ul>

<p>And the total complexity is: <img src="https://betterexplained.com/latex/caf4354a88182d1d3573.png" alt="$O(n\log(n)) + O(n\log(n)) + O(n) + O(n\log(n)) = O(n\log(n))$" width="489" height="19" style="vertical-align:-4.53px" class="bex-math"></img></p>

<p>Regular multiplication in the fancy domain is <em>faster</em> than a fancy multiplication in the regular domain. Our French friend is no slouch. (<a href="http://www.ams.org/publicoutreach/feature-column/fcarc-multiplication">More</a>)</p>

<h3><span id="Convolutional_Neural_Nets_CNN">Convolutional Neural Nets (CNN)</span></h3>

<p>Machine learning is about discovering the math functions that transform input data into a desired result (a prediction, classification, etc.).</p>

<p>Starting with an input signal, we could convolve it with a bunch of kernels:</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/ec62a4fc08cd4f262a0f7fa9221eef1e.png' width='229' height='16' alt='\displaystyle{\text{input} * k_1 * k_2 * k_3 ... = \text{result}}' class='tex'></p>

<p>Given that convolution can do complex math (moving averages, blurs, derivatives...), it seems <em>some</em> combination of kernels should turn our input into something useful, right?</p>

<p>Convolutional Neural Nets (CNNs) process an input with layers of kernels, optimizing their weights (plans) to reach a goal. Imagine tweaking the treatment plan to keep medicine usage below some threshold.</p>

<p>CNNs are often used with image classifiers, but 1D data sets work just fine.</p>

<ul>
<li>Nice writeup: <a href="https://ujjwalkarn.me/2016/08/11/intuitive-explanation-convnets/">https://ujjwalkarn.me/2016/08/11/intuitive-explanation-convnets/</a></li>
<li>Digit classifier demo: <a href="https://cs.stanford.edu/people/karpathy/convnetjs/demo/mnist.html">https://cs.stanford.edu/people/karpathy/convnetjs/demo/mnist.html</a></li>
</ul>

<h3><span id="LTI_System_Behavior">LTI System Behavior</span></h3>

<p>A linear, time-invariant system means:</p>

<ul>
<li>Linear: Scaling and combining inputs scales and combines outputs by the same amount</li>
<li>Time invariant: Outputs depend on relative time, not absolute time. You get 3 units on <em>your</em> first day, and it doesn't matter if it's Wednesday or Thursday.</li>
</ul>

<p>A fancy phrase is "A LTI system is characterized by its impulse response". Translation: If we send a <em>single</em> patient through the hospital <code>[1]</code>, we'll discover the treatment plan. Then we can predict the usage for <em>any</em> sequence of patients by convolving it with the plan.</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/1ed77a8b2cc34caedc58aa7b05416c35.png' width='352' height='17' alt='\displaystyle{\text{system response} = \text{impulse response} * \text{inputs}}' class='tex'></p>

<p>If the system isn't LTI, we can't extrapolate based on a <em>single</em> person's experience. Scaling the inputs may not scale the outputs, and the actual calendar day, not relative day, may impact the result (imagine fewer rooms available on weekends).</p>

<h3><span id="Engineering_Analogies">Engineering Analogies</span></h3>

<p>From <a href="https://www.quora.com/What-is-an-intuitive-explanation-for-convolution/answer/David-Greenspan">David Greenspan</a>: "Suppose you have a special laser pointer that makes a star shape on the wall. You tape together a bunch of these laser pointers in the shape of a square. The pattern on the wall now is the convolution of a star with a square."</p>

<p>Regular multiplication gives you a single scaled copy of an input. Convolution creates multiple overlapping copies that follow a pattern you've specified.</p>

<p>Real-world systems have squishy, not instantaneous, behavior: they ramp up, peak, and drop down. The convolution lets us model systems that echo, reverb and overlap.</p>

<p>Now it's time for the famous sliding window example. Think of a pulse of inputs (red) sliding through a system (blue), and having a combined effect (yellow): the convolution.</p>

<p><img decoding="async" src="https://upload.wikimedia.org/wikipedia/commons/b/b9/Convolution_of_spiky_function_with_box2.gif" alt="Intuitive Guide to Convolution" /></p>

<p>(<a href="https://commons.wikimedia.org/wiki/File:Convolution_of_spiky_function_with_box2.gif">Source</a>)</p>

<h2><span id="Summary">Summary</span></h2>

<p>Convolution has an advanced technical definition, but the basics can be understood with the right analogy.</p>

<p>Quick rant: I study math for fun, yet it took years to find a satisfying intuition for:</p>

<ul>
<li>Why is one function reversed?</li>
<li>Why is convolution commutative?</li>
<li>Why does the integral of the convolution = product of integrals?</li>
<li>Why are the Fourier Transforms multiplied point-by-point, and not overlapped?</li>
</ul>

<p>Why'd it take so long? Imagine learning multiplication with <img src="https://betterexplained.com/latex/159fcc70dfe383db4f8e.png" alt="$f \times g = z$" width="74" height="17" style="vertical-align:-3.71px" class="bex-math"></img> instead of  <img src="https://betterexplained.com/latex/06251d1d8858978ebc28.png" alt="$3 \times 5 = 15$" width="83" height="14" style="vertical-align:-1.49px" class="bex-math"></img>. Without an example I can explore <em>in my head</em>, I could only memorize results, not intuit them. Hopefully this analogy can save you years of struggle.</p>

<p>Happy math.</p>

]]></content:encoded>
					
					<wfw:commentRss>https://betterexplained.com/articles/intuitive-convolution/feed/</wfw:commentRss>
			<slash:comments>33</slash:comments>
		

			</item>
	<item>
		<title>An Interactive Guide To The Fourier Transform</title>
		<link>https://betterexplained.com/articles/an-interactive-guide-to-the-fourier-transform/</link>
					<comments>https://betterexplained.com/articles/an-interactive-guide-to-the-fourier-transform/#disqus_thread</comments>
		
		<dc:creator><![CDATA[kalid]]></dc:creator>
		<pubDate>Thu, 20 Dec 2012 03:30:10 +0000</pubDate>
				<category><![CDATA[Math]]></category>
				<category><![CDATA[Popular]]></category>
				<category><![CDATA[Fourier Transform]]></category>
		<guid isPermaLink="false">http://betterexplained.com/?p=2851</guid>

					<description><![CDATA[The Fourier Transform is one of the deepest insights ever made. Unfortunately, the meaning is buried within dense equations: Yikes. Rather than jumping into the symbols, let's experience the key idea firsthand. Here's a plain-English metaphor: What does the Fourier Transform do? Given a smoothie, it finds the recipe. How? Run the smoothie through filters [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>The Fourier Transform is one of the deepest insights ever made. Unfortunately, the meaning is buried within dense equations:</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/45c088dbb767150fc0bacfeb49dd49e5.png' width='189' height='54' alt='\displaystyle{X_k = \sum_{n=0}^{N-1} x_n \cdot e^{-i 2 \pi k n / N}}' class='tex'></p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/faeb9c5bf2e60add63ae4a70b293c7b4.png' width='202' height='54' alt='\displaystyle{x_n = \frac{1}{N} \sum_{k=0}^{N-1} X_k \cdot e^{i 2 \pi k n / N}}' class='tex'></p>

<p>Yikes. Rather than jumping into the symbols, let's experience the key idea firsthand. Here's a plain-English metaphor:</p>

<ul>
<li><strong>What does the Fourier Transform do?</strong> Given a smoothie, it finds the recipe.</li>
<li><strong>How?</strong> Run the smoothie through filters to extract each ingredient.</li>
<li><strong>Why?</strong> Recipes are easier to analyze, compare, and modify than the smoothie itself.</li>
<li><strong>How do we get the smoothie back?</strong> Blend the ingredients.</li>
</ul>

<p>Here's the "math English" version of the above:</p>

<ul>
<li>The Fourier Transform takes a time-based pattern, measures every possible cycle, and returns the overall "cycle recipe" (the amplitude, offset, &amp; rotation speed for every cycle that was found).</li>
</ul>

<p>Time for the equations? No! Let's get our hands dirty and <em>experience</em> how any pattern can be built with cycles, with live simulations.</p>

<p>If all goes well, we'll have an aha! moment and intuitively realize why the Fourier Transform is possible. We'll save the detailed math analysis for the follow-up.</p>

<p>This isn't a force-march through the equations, it's the casual stroll I wish I had. Onward!</p>

<div style="position:relative;height:0;padding-bottom:56.25%"><iframe src="https://www.youtube.com/embed/iN0VG9N2q0U?ecver=2" width="640" height="360" frameborder="0" style="position:absolute;width:100%;height:100%;left:0" allowfullscreen></iframe></div>

<h2>From Smoothie to Recipe</h2>

<p>A math transformation is a change of perspective. We change our notion of quantity from "single items" (lines in the sand, tally system) to "groups of 10" (decimal) depending on what we're counting. Scoring a game? Tally it up. Multiplying? Decimals, please.</p>

<p>The Fourier Transform changes our perspective from consumer to producer, turning <em>What do I have?</em> into <em>How was it made?</em></p>

<p>In other words: given a smoothie, let's find the recipe.</p>

<p>Why? Well, recipes are great descriptions of drinks. You wouldn't share a drop-by-drop analysis, you'd say "I had an orange/banana smoothie". A recipe is more easily categorized, compared, and modified than the object itself.</p>

<p>So... given a smoothie, how do we find the recipe?</p>

<p><img decoding="async" alt="fourier transform analogy smoothie to recipe" src="https://betterexplained.com/wp-content/uploads/images/smoothie-to-recipe-20121030-223058.png" height="300" class="webpexpress-processed"></p>

<p>Well, imagine you had a few filters lying around:</p>

<ul>
<li>Pour through the "banana" filter. 1 oz of bananas are extracted.</li>
<li>Pour through the "orange" filter. 2 oz of oranges.</li>
<li>Pour through the "milk" filter. 3 oz of milk.</li>
<li>Pour through the "water" filter. 3 oz of water.</li>
</ul>

<p>We can reverse-engineer the recipe by filtering each ingredient. The catch?</p>

<ul>
<li><p><strong>Filters must be independent</strong>. The banana filter needs to capture bananas, and nothing else. Adding more oranges should never affect the banana reading.</p></li>
<li><p><strong>Filters must be complete</strong>. We won't get the real recipe if we leave out a filter ("There were mangoes too!"). Our collection of filters must catch every possible ingredient.</p></li>
<li><p><strong>Ingredients must be combine-able</strong>. Smoothies can be separated and re-combined without issue (A cookie? Not so much. Who wants crumbs?). The ingredients, when separated and combined in any order, must make the same result.</p></li>
</ul>

<h2>See The World As Cycles</h2>

<p>The Fourier Transform takes a specific viewpoint: <strong>What if any signal could be filtered into a bunch of circular paths?</strong></p>

<p>Whoa. This concept is mind-blowing, and poor Joseph Fourier had his idea rejected at first. (<em>Really Joe, even a staircase pattern can be made from circles?</em>)</p>

<p>And despite <a href="http://wiki.answers.com/Q/What_is_the_history_of_fourier_series">decades of debate</a> in the math community, we expect students to internalize the idea without issue. Ugh. Let's walk through the intuition.</p>

<p>The Fourier Transform finds the recipe for a signal, like our smoothie process:</p>

<ul>
<li>Start with a time-based signal</li>
<li>Apply filters to measure each possible "circular ingredient"</li>
<li>Collect the full recipe, listing the amount of each "circular ingredient"</li>
</ul>

<p>Stop. Here's where most tutorials excitedly throw engineering applications at your face. Don't get scared; think of the examples as "Wow, we're finally seeing the source code (DNA) behind previously confusing ideas".</p>

<ul>
<li><p>If earthquake vibrations can be separated into "ingredients" (vibrations of different speeds &amp; amplitudes), buildings can be designed to avoid interacting with the strongest ones.</p></li>
<li><p>If sound waves can be separated into ingredients (bass and treble frequencies), we can boost the parts we care about, and hide the ones we don't. The crackle of random noise can be removed. Maybe similar "sound recipes" can be compared (music recognition services compare recipes, not the raw audio clips).</p></li>
<li><p>If computer data can be represented with oscillating patterns, perhaps the least-important ones can be ignored. This "lossy compression" can drastically shrink file sizes (and why JPEG and MP3 files are much smaller than raw .bmp or .wav files).</p></li>
<li><p>If a radio wave is our signal, we can use filters to listen to a particular channel. In the smoothie world, imagine each person paid attention to a different ingredient: Adam looks for apples, Bob looks for bananas, and Charlie gets cauliflower (sorry bud).</p></li>
</ul>

<p>The Fourier Transform is useful in engineering, sure, but it's a metaphor about finding the root causes behind an observed effect.</p>

<h2>Think With Circles, Not Just Sinusoids</h2>

<p>One of my giant confusions was separating the definitions of "sinusoid" and "circle".</p>

<ul>
<li>A "sinusoid" is a specific back-and-forth pattern (a <a href="https://betterexplained.com/articles/intuitive-understanding-of-sine-waves/">sine</a> or cosine wave), and 99% of the time, it refers to motion in one dimension.</li>
<li>A "circle" is a round, 2d pattern you probably know. If you enjoy using 10-dollar words to describe 10-cent ideas, you might call a circular path a "complex sinusoid".</li>
</ul>

<p>Labeling a circular path as a "complex sinusoid" is like describing a word as a "multi-letter". You zoomed into the wrong level of detail. Words are about concepts, not the letters they can be split into!</p>

<p>The Fourier Transform is about circular paths (not 1-d sinusoids) and <a href="https://betterexplained.com/articles/intuitive-understanding-of-eulers-formula/">Euler's formula</a> is a clever way to generate one:</p>

<p><img decoding="async" src="https://betterexplained.com/wp-content/uploads/euler/equal_paths.png" alt="euler path" class="webpexpress-processed"></p>

<p>Must we use imaginary exponents to move in a circle? Nope. But it's convenient and compact. And sure, we can describe our path as coordinated motion in two dimensions (real and imaginary), but don't forget the big picture: we're just moving in a circle.</p>

<h2>Following Circular Paths</h2>

<p>Let's say we're chatting on the phone and, like usual, I want us to draw the same circle simultaneously. (<em>You promised!</em>) What should I say?</p>

<ul>
<li>How big is the circle? (Amplitude, i.e. size of radius)</li>
<li>How fast do we draw it? (Frequency. 1 circle/second is a frequency of 1 Hertz (Hz) or 2*pi radians/sec)</li>
<li>Where do we start? (Phase angle, where 0 degrees is the x-axis)</li>
</ul>

<p>I could say "2-inch radius, start at 45 degrees, 1 circle per second, go!". After half a second, we should each be pointing to: starting point + amount traveled = 45 + 180 = 225 degrees (on a 2-inch circle).</p>

<p><img decoding="async" alt="circular path with parameters" src="https://betterexplained.com/wp-content/uploads/images/circular-path-parameters-20121201-203317.png" width="500" class="webpexpress-processed"></p>

<p>Every circular path needs a size, speed, and starting angle (amplitude/frequency/phase). We can even combine paths: imagine tiny motorcars, driving in circles at different speeds.</p>

<p>The combined position of <em>all the cycles</em> is our signal, just like the combined flavor of <em>all the ingredients</em> is our smoothie.</p>

<p>Here's a simulation of a basic circular path:</p>

<iframe src="https://betterexplained.com/examples/fourier/?cycles=0,1" width="550px" height="280px" frameborder="0"></iframe>

<p>(Based on <a href="https://web.archive.org/web/20140320040804/http://treeblurb.com/dev_math/sin_canv00.html">this animation</a>, here's <a href="https://gist.github.com/kazad/8bb682da198db597558c">the source code</a>. Modern browser required. Click the graph to pause/unpause.)</p>

<p>The magnitude of each cycle is listed in order, starting at 0Hz. Cycles <code>[0 1]</code> means</p>

<ul>
<li>0 amplitude for the 0Hz cycle (0Hz = a constant cycle, stuck on the x-axis at zero degrees)</li>
<li>1 amplitude for the 1Hz cycle (completes 1 cycle per time interval)</li>
</ul>

<p>Now the tricky part:</p>

<ul>
<li><strong>The blue graph measures the <em>real part</em> of the cycle</strong>. Another lovely math confusion: the real axis of the circle, which is usually horizontal, has its magnitude shown on the vertical axis. You can mentally rotate the circle 90 degrees if you like.</li>
<li><strong>The time points are spaced at the fastest frequency</strong>. A 1Hz signal needs 2 time points for a start and stop (a single data point doesn't have a frequency). The time values <code>[1 -1]</code> shows the amplitude at these equally-spaced intervals.</li>
</ul>

<p>With me? <code>[0 1]</code> is a pure 1Hz cycle.</p>

<p>Now let's add a 2Hz cycle to the mix. <code>[0 1 1]</code> means "Nothing at 0Hz, 1Hz of amplitude 1, 2Hz of amplitude 1":</p>

<iframe src="https://betterexplained.com/examples/fourier/?cycles=0,1,1" width="550px" height="280px" frameborder="0"></iframe>

<p>Whoa. The little motorcars are getting wild: the green lines are the 1Hz and 2Hz cycles, and the blue line is the combined result. Try toggling the green checkbox to see the final result clearly. The combined "flavor" is a sway that starts at the max and dips low for the rest of the interval.</p>

<p>The yellow dots are when we actually measure the signal. With 3 cycles defined (0Hz, 1Hz, 2Hz), each dot is 1/3 of the way through the signal. In this case, cycles <code>[0 1 1]</code> generate the time values <code>[2 -1 -1]</code>, which starts at the max (2) and dips low (-1).</p>

<p>Oh! We can't forget phase, the starting angle! Use <code>magnitude:angle</code> to set the phase. So <code>[0 1:45]</code> is a 1Hz cycle that starts at 45 degrees:</p>

<iframe src="https://betterexplained.com/examples/fourier/?cycles=0,1:45" width="550px" height="280px" frameborder="0"></iframe>

<p>This is a shifted version of <code>[0 1]</code>. On the time side we get <code>[.7 -.7]</code> instead of <code>[1 -1]</code>, because our cycle isn't exactly lined up with our measuring intervals, which are still at the halfway point (this could be desired!).</p>

<p><strong>The Fourier Transform finds the set of cycle speeds, amplitudes and phases to match any time signal.</strong></p>

<p>Our signal becomes an abstract notion that we consider as "observations in the time domain" or "ingredients in the frequency domain".</p>

<p>Enough talk: try it out! In the simulator, type any time or cycle pattern you'd like to see. If it's time points, you'll get a collection of cycles (that combine into a "wave") that matches your desired points.</p>

<p><a href="https://betterexplained.com/wp-content/uploads/images/time-patterns-20121205-164541.png" target="_blank" rel="noopener">
<img decoding="async" alt="fourier transform examples" src="https://betterexplained.com/wp-content/uploads/images/time-patterns-20121205-164541.png" width="550px" class="webpexpress-processed"></a></p>

<p>But… doesn't the combined wave have strange values between the yellow time intervals? Sure. But who's to say whether a signal travels in straight lines, or curves, or zips into other dimensions when we aren't measuring it? It behaves exactly as we need at the equally-spaced moments we asked for.</p>

<h2>Making A Spike In Time</h2>

<p>Can we make a spike in time, like <code>(4 0 0 0)</code>, using cycles? I'll use parentheses <code>()</code> for a sequence of time points, and brackets <code>[]</code> for a sequence of cycles.</p>

<p>Although the spike seems boring to us time-dwellers (<em>one data point, that's it?</em>), think about the complexity in the cycle world. Our cycle ingredients must start aligned (at the max value, 4) and then "explode outwards", each cycle with partners that cancel it in the future. Every remaining point is zero, which is a tricky balance with multiple cycles running around (we can't just "turn them off").</p>

<p>Let's walk through each time point:</p>

<ul>
<li><p>At time 0, the first instant, every cycle ingredient is at its max. Ignoring the other time points, <code>(4 ? ? ?)</code> can be made from 4 cycles (0Hz 1Hz 2Hz 3Hz), each with a magnitude of 1 and phase of 0 (i.e., 1 + 1 + 1 + 1 = 4).</p></li>
<li><p>At every future point (t = 1, 2, 3), the sum of all cycles must cancel.</p></li>
</ul>

<p>Here's the trick: when two cycles are on opposites sides of the circle (North &amp; South, East &amp; West, etc.) their combined position is zero (3 cycles can cancel if they're spread evenly at 0, 120, and 240 degrees).</p>

<p>Imagine a constellation of points moving around the circle. Here's the position of each cycle at every instant:</p>

<pre>Time 0 1 2 3 
------------
0Hz: 0 0 0 0 
1Hz: 0 1 2 3
2Hz: 0 2 0 2
3Hz: 0 3 2 1
</pre>

<p>Notice how the 3Hz cycle starts at 0, gets to position 3, then position "6" (with only 4 positions, 6 <a href="https://betterexplained.com/articles/fun-with-modular-arithmetic/">modulo</a> 4 = 2), then position "9" (9 modulo 4 = 1).</p>

<p>When our cycle is 4 units long, cycle speeds a half-cycle apart (2 units) will either be lined up (difference of 0, 4, 8…) or on opposite sides (difference of 2, 6, 10…).</p>

<p>OK. Let's drill into each time point:</p>

<ul>
<li>Time 0: All cycles at their max (total of 4)</li>
<li>Time 1: 1Hz and 3Hz cancel (positions 1 &amp; 3 are opposites), 0Hz and 2Hz cancel as well. The net is 0.</li>
<li>Time 2: 0Hz and 2Hz line up at position 0, while 1Hz and 3Hz line up at position 2 (the opposite side). The total is still 0.</li>
<li>Time 3: 0Hz and 2Hz cancel. 1Hz and 3Hz cancel.</li>
<li>Time 4 (repeat of t=0): All cycles line up.</li>
</ul>

<p>The trick is having individual speeds cancel (0Hz vs 2Hz, 1Hz vs 3Hz), or having the lined-up pairs cancel (0Hz + 2Hz vs 1Hz + 3Hz).</p>

<p>When every cycle has equal power and 0 phase, we start aligned and cancel afterwards. (I don't have a nice proof yet -- any takers? -- but you can see it yourself. Try <code>[1 1]</code>, <code>[1 1 1]</code>, <code>[1 1 1 1]</code> and notice the signals we generate: <code>(2 0)</code>, <code>(3 0 0)</code>, <code>(4 0 0 0)</code>).</p>

<p>In my head, I label these signals as "time spikes": they have a value for a single instant, and are zero otherwise (the fancy name is a <a href="https://en.wikipedia.org/wiki/Dirac_delta_function">delta function</a>.)</p>

<p>Here's how I visualize the initial alignment, followed by a net cancellation:</p>

<p><img decoding="async" alt="fourier transform constructive and destructive interference" src="https://betterexplained.com/wp-content/uploads/images/fourier-interference-20121211-171719.png" width="400px" class="webpexpress-processed"></p>

<h2>Moving The Time Spike</h2>

<p>Not everything happens at t=0. Can we change our spike to <code>(0 4 0 0)</code>?</p>

<p>It seems the cycle ingredients should be similar to <code>(4 0 0 0)</code>, but the cycles must align at t=1 (one second in the future). Here's where phase comes in.</p>

<p>Imagine a race with 4 runners. Normal races have everyone lined up at the starting line, the <code>(4 0 0 0)</code> time pattern. Boring.</p>

<p>What if we want everyone to <em>finish</em> at the same time? Easy. Just move people forward or backwards by the appropriate distance. Maybe granny can start 2 feet in front of the finish line, Usain Bolt can start 100m back, and they can cross the tape holding hands.</p>

<p>Phase shifts, the starting angle, are delays in the cycle universe. Here's how we adjust the starting position to delay every cycle 1 second:</p>

<ul>
<li>A 0Hz cycle doesn't move, so it's already aligned</li>
<li>A 1Hz cycle goes 1 revolution in the entire 4 seconds, so a 1-second delay is a quarter-turn. Phase shift it 90 degrees backwards (-90) and it gets to phase=0, the max value, at t=1.</li>
<li>A 2Hz cycle is twice as fast, so give it twice the angle to cover (-180 or 180 phase shift -- it's across the circle, either way).</li>
<li>A 3Hz cycle is 3x as fast, so give it 3x the distance to move (-270 or +90 phase shift)</li>
</ul>

<p>If time points <code>(4 0 0 0)</code> are made from cycles <code>[1 1 1 1]</code>, then time points <code>(0 4 0 0)</code> are made from <code>[1 1:-90 1:180 1:90]</code>. (Note: I'm using "1Hz", but I mean "1 cycle over the entire time period").</p>

<p>Whoa -- we're working out the cycles in our head!</p>

<p>The interference visualization is similar, except the alignment is at t=1.</p>

<p><img decoding="async" alt="fourier transform time spike" src="https://betterexplained.com/wp-content/uploads/images/delayed-spike-20121214-162623.png" width="400px" class="webpexpress-processed"></p>

<p>Test your intuition: Can you make <code>(0 0 4 0)</code>, i.e. a 2-second delay? 0Hz has no phase. 1Hz has 180 degrees, 2Hz has 360 (aka 0), and 3Hz has 540 (aka 180), so it's <code>[1 1:180 1 1:180]</code>.</p>

<h2>Discovering The Full Transform</h2>

<p>The big insight: our signal is just a bunch of time spikes! If we merge the recipes for each time spike, we should get the recipe for the full signal.</p>

<p>The Fourier Transform builds the recipe frequency-by-frequency:</p>

<ul>
<li>Separate the full signal (a b c d) into "time spikes": (a 0 0 0) (0 b 0 0) (0 0 c 0) (0 0 0 d)</li>
<li>For any frequency (like 2Hz), the <em>tentative</em> recipe is "a/4 + b/4 + c/4 + d/4" (the amplitude of each spike is split among all frequencies)</li>
<li>Wait! We need to offset each spike with a phase delay (the angle for a "1 second delay" depends on the frequency).</li>
<li>Actual recipe for a frequency = a/4 (no offset) + b/4 (1 second offset) + c/4 (2 second offset) + d/4 (3 second offset).</li>
</ul>

<p>We can then loop through every frequency to get the full transform.</p>

<p>Here's the conversion from "math English" to full math:</p>

<p><img decoding="async" alt="fourier transform plain english" src="https://betterexplained.com/wp-content/uploads/images/fourier-explained-20121219-224649.png" width="500px" class="webpexpress-processed"></p>

<p>A few notes:</p>

<ul>
<li>N = number of time samples we have</li>
<li>n = current sample we're considering (0 .. N-1)</li>
<li>x<sub>n</sub> = value of the signal at time n</li>
<li>k = current frequency we're considering (0 Hertz up to N-1 Hertz)</li>
<li>X<sub>k</sub> = amount of frequency k in the signal (amplitude and phase, a complex number)</li>
<li>The 1/N factor is usually moved to the <em>reverse transform</em> (going from frequencies back to time). This <a href="http://math.stackexchange.com/questions/58163/dft-why-are-the-definitions-for-inverse-and-forward-commonly-switched">is allowed</a>, though I prefer 1/N in the forward transform since it gives the <em>actual</em> sizes for the time spikes. You can get wild and even use <img src="https://betterexplained.com/latex/7c865975e451d5e3eebe.png" alt="$1/\sqrt{N}$" width="50" height="23" style="vertical-align:-4.53px" class="bex-math"></img> on both transforms (going forward and back creates the 1/N factor).</li>
<li>n/N is the percent of the time we've gone through. 2 * pi * k is our speed in radians / sec. e^-ix is our backwards-moving circular path. The combination is how far we've moved, for this speed and time.</li>
<li>The raw equations for the Fourier Transform just say "add the complex numbers". Many programming languages cannot handle complex numbers directly, so you convert everything to rectangular coordinates and add those.</li>
</ul>

<h2>Onward</h2>

<p>This was my most challenging article yet. The Fourier Transform has several flavors (discrete/continuous/finite/infinite), covers deep math (Dirac delta functions), and it's easy to get lost in details. I was constantly bumping into the edge of my knowledge.</p>

<p>But there's always simple analogies out there -- I refuse to think otherwise. Whether it's a smoothie or Usain Bolt &amp; Granny crossing the finish line, take a simple understanding and refine it. The analogy is flawed, and that's ok: it's a raft to use, and leave behind once we cross the river.</p>

<p>I realized how feeble my own understanding was when I couldn't work out the transform of <code>(1 0 0 0)</code> in my head. For me, it was like saying I knew addition but, gee whiz, I'm not sure what "1 + 1 + 1 + 1" would be. Why not? Shouldn't we have an intuition for the simplest of operations?</p>

<p>That discomfort led me around the web to build my intuition. In addition to the references in the article, I'd like to thank:</p>

<ul>
<li><a href="http://www.scotthyoung.com/blog/">Scott Young</a>, for the initial impetus for this post</li>
<li><a href="http://shaheengandhi.com">Shaheen Gandhi</a>, Roger Cheng, and <a href="http://britcruise.com/">Brit Cruise</a> for kicking around ideas &amp; refining the analogy</li>
<li><a href="http://cns-alumni.bu.edu/~slehar/fourier/fourier.html">Steve Lehar</a> for great examples of the Fourier Transform on images</li>
<li><a href="http://www.complextoreal.com/chapters/fft1.pdf">Charan Langton</a> for her detailed walkthrough</li>
<li><a href="https://ccrma.stanford.edu/~jos/log/">Julius Smith</a> for a fantastic walkthrough of the Discrete Fourier Transform (what we covered today)</li>
<li><a href="http://worrydream.com/#!/LearnableProgramming">Bret Victor</a> for his techniques on visualizing learning</li>
</ul>

<p>Today's goal was to <em>experience</em> the Fourier Transform. We'll save the advanced analysis for next time.</p>

<p>Happy math.</p>

<h2>Appendix: Projecting Onto Cycles</h2>

<p>Stuart Riffle has a <a href="https://web.archive.org/web/20120418231513/http://www.altdevblogaday.com/2011/05/17/understanding-the-fourier-transform/">great interpretation</a> of the Fourier Transform:</p>

<p><img decoding="async" alt="fourier transform colorized" src="https://betterexplained.com/wp-content/uploads/images/DerivedDFT.png" class="webpexpress-processed"></p>

<p>Imagine spinning your signal in a centrifuge and checking for a bias. I have a correction: we must spin <em>backwards</em> (the exponent in the equation above should be <img src="https://betterexplained.com/latex/838f64d5cea6b214b1e0.png" alt="$e^{-i 2 \pi...}$" width="49" height="16" style="vertical-align:-0.2px" class="bex-math"></img>). You already know why: we need a phase <em>delay</em> so spikes appear in the <em>future</em>.</p>

<h2>Appendix: Another Awesome Visualization</h2>

<p><a href="http://toxicdump.org/blog/">Lucas Vieira</a>, author of excellent <a href="https://en.wikipedia.org/wiki/User:Kieff/Gallery">Wikipedia animations</a>, was <a href="http://blog.matthen.com/post/42112703604/the-smooth-motion-of-rotating-circles-can-be-used">inspired</a> to make this interactive animation:</p>

<p><a href="https://web.archive.org/web/20170201145911/http://toxicdump.org/stuff/FourierToy.swf">Fourier Toy - Click to download, requires flash</a></p>

<p><a href="http://toxicdump.org/stuff/FourierToy.swf"><img decoding="async" class="alignnone size-medium wp-image-5267" src="https://betterexplained.com/wp-content/uploads/2012/12/Fourier_Toy-300x126.png" alt="Fourier_Toy" width="300" height="126" srcset="https://betterexplained.com/wp-content/uploads/2012/12/Fourier_Toy-300x126.png 300w, https://betterexplained.com/wp-content/uploads/2012/12/Fourier_Toy-768x323.png 768w, https://betterexplained.com/wp-content/uploads/2012/12/Fourier_Toy-1024x431.png 1024w, https://betterexplained.com/wp-content/uploads/2012/12/Fourier_Toy-320x135.png 320w, https://betterexplained.com/wp-content/uploads/2012/12/Fourier_Toy-200x84.png 200w, https://betterexplained.com/wp-content/uploads/2012/12/Fourier_Toy-400x168.png 400w, https://betterexplained.com/wp-content/uploads/2012/12/Fourier_Toy.png 1438w" sizes="(max-width: 300px) 100vw, 300px"></a></p>
<!--



<iframe src="https://toxicdump.org/stuff/FourierToy.swf" width="500" height="212" style="border:none;"></iframe>


-->

<p>(<a href="http://www.reddit.com/r/math/comments/17v8cv/visualized_fourier/c89c3pa">Detailed list</a> of control options)</p>

<p>The Fourier Transform is about cycles added to cycles added to cycles. Try making a "time spike" by setting a amplitude of 1 for every component (press Enter after inputting each number). Fun fact: with enough terms, you can draw any shape, even <a href="https://www.youtube.com/watch?v=QVuU2YCwHjw&amp;feature=youtu.be">Homer Simpson</a>.</p>

<iframe src="https://www.youtube.com/embed/QVuU2YCwHjw" width="420" height="315" frameborder="0" allowfullscreen="allowfullscreen"></iframe>

<p>Check out <a href="http://www.jezzamon.com/fourier/">http://www.jezzamon.com/fourier/</a> for a great tool to draw any shape using epicycles.</p>

<p><a href="http://www.jezzamon.com/fourier/"><img alt="An Interactive Guide To The Fourier Transform" decoding="async" src="https://betterexplained.com/wp-content/uploads/2019/01/Fourier-Transforms-2019-01-12-15-11-48.png" width="500" class="webpexpress-processed">
</a></p>

<h2>Appendix: Article with R code samples</h2>

<p>João Neto made a great writeup, with technical (R) code samples here:</p>

<p><a href="http://www.di.fc.ul.pt/~jpn/r/fourier/fourier.html">http://www.di.fc.ul.pt/~jpn/r/fourier/fourier.html</a></p>

<h2>Appendix: Using the code</h2>

<p>All the code and examples are open source (MIT licensed, do what you like).</p>

<ul>
<li><a href="https://betterexplained.com/examples/fourier/">Interactive example</a> (view source)</li>
<li><a href="https://gist.github.com/129d477ddb1c8025c9ac">Github gist</a></li>
<li><a href="http://www.reddit.com/r/programming/comments/156a9i/an_interactive_guide_to_the_fourier_transform/c7k9b1t?context=3">Reddit discussion</a> on details of the computation, I'm pb_zeppelin</li>
</ul>

]]></content:encoded>
					
					<wfw:commentRss>https://betterexplained.com/articles/an-interactive-guide-to-the-fourier-transform/feed/</wfw:commentRss>
			<slash:comments>478</slash:comments>
		

			</item>
	</channel>
</rss>
