<?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>BetterExplained</title>
	<atom:link href="http://betterexplained.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://betterexplained.com</link>
	<description>Learn Right, Not Rote.</description>
	<lastBuildDate>Fri, 10 May 2013 20:47:49 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=</generator>
		<item>
		<title>An Intuitive Introduction To Limits</title>
		<link>http://betterexplained.com/articles/an-intuitive-introduction-to-limits/</link>
		<comments>http://betterexplained.com/articles/an-intuitive-introduction-to-limits/#comments</comments>
		<pubDate>Mon, 15 Apr 2013 17:11:13 +0000</pubDate>
		<dc:creator>kalid</dc:creator>
				<category><![CDATA[Calculus]]></category>
		<category><![CDATA[Math]]></category>

		<guid isPermaLink="false">http://betterexplained.com/?p=3051</guid>
		<description><![CDATA[Limits, the Foundations Of Calculus, seem so artificial and weasely: &#8220;Let x <em>approach</em> 0, but not get there, yet we&#8217;ll act like it&#8217;s there… &#8221; Ugh. Here&#8217;s how I learned to enjoy them:

<ul>
<li><strong>What is a limit?</strong> Our best prediction </li>&#8230; <a href="http://betterexplained.com/articles/an-intuitive-introduction-to-limits/" class="read_more">Read article</a></ul>]]></description>
				<content:encoded><![CDATA[<p>Limits, the Foundations Of Calculus, seem so artificial and weasely: &#8220;Let x <em>approach</em> 0, but not get there, yet we&#8217;ll act like it&#8217;s there… &#8221; Ugh. Here&#8217;s how I learned to enjoy them:</p>

<ul>
<li><strong>What is a limit?</strong> Our best prediction of a point we didn&#8217;t observe.</li>
<li><strong>How do we make a prediction?</strong> Zoom into the neighboring points. If a certain prediction is always in-between neighboring points, no matter how much we zoom, that&#8217;s our estimate.</li>
<li><strong>Why do we need limits?</strong> Math has &#8220;black hole&#8221; scenarios (dividing by zero, going to infinity), and limits give us a reasonable estimate.</li>
<li><strong>How do we know we&#8217;re right?</strong> We don&#8217;t. Our prediction, the limit, isn&#8217;t required to match reality. But for most natural phenomena, it sure seems to.</li>
</ul>

<p>Limits let us ask &#8220;What if?&#8221;. If we can directly observe a function at a value (like x=0, or x growing infinitely), we don&#8217;t need a prediction. The limit wonders, &#8220;If you can see everything <em>except</em> a single value, what do you think is there?&#8221;.</p>

<p>When our prediction is <strong>consistent and improves the closer we look</strong>, we feel confident in it. And if the function behaves smoothly, like most real-world functions do, the limit is where the missing point must be.</p>

<h2>Key Analogy: Predicting A Soccer Ball</h2>

<p>Pretend you&#8217;re watching a <a href="http://www.youtube.com/watch?v=2vJn5XxWg9U">soccer game</a>. Unfortunately, the connection is choppy:</p>

<p><img src="http://betterexplained.com/wp-content/uploads/limit_intro/soccer-limits.jpg" alt="soccer limits" /></p>

<p>Ack! We missed what happened at 4:00. Even so, what&#8217;s your prediction for the ball&#8217;s position?</p>

<p>Easy. Just grab the neighboring instants (3:59 and 4:01) and predict the ball to be somewhere in-between.</p>

<p>And… it works! Real-world objects don&#8217;t teleport; they move through intermediate positions along their path from A to B. Our prediction is &#8220;At 4:00, the ball was between its position at 3:59 and 4:01&#8243;. Not bad.</p>

<p>With a slow-motion camera, we might even say &#8220;At 4:00, the ball was between its positions at 3:59.999 and 4:00.001&#8243;.</p>

<p>Our prediction is feeling solid. Can we articulate why?</p>

<ul>
<li><p><strong>The predictions agree at increasing zoom levels</strong>. Imagine the 3:59-4:01 range was 9.9-10.1 meters, but after zooming into 3:59.999-4:00.001, the range widened to 9-12 meters. Uh oh! Zooming should <em>narrow</em> our estimate, not make it worse! Not every zoom level needs to be accurate (imagine seeing the game every 5 minutes), but to feel confident, there must be some threshold where subsequent zooms only strengthen our range estimate.</p></li>
<li><p><strong>The before-and-after agree.</strong> Imagine at 3:59 the ball was at 10 meters, rolling right, and at 4:01 it was at 50 meters, rolling left. What happened? We had a sudden jump (a camera change?) and now we can&#8217;t pin down the ball&#8217;s position. Which one had the ball at 4:00? This ambiguity shatters our ability to make a confident prediction.</p></li>
</ul>

<p>With these requirements in place, we might say &#8220;At 4:00, the ball was at 10 meters. This estimate is confirmed by our initial zoom (3:59-4:01, which estimates 9.9 to 10.1 meters) and the following one (3:59.999-4:00.001, which estimates 9.999 to 10.001 meters)&#8221;.</p>

<p>Limits are a strategy for making confident predictions.</p>

<h2>Exploring The Intuition</h2>

<p>Let&#8217;s not bring out the math definitions just yet. What things, in the <em>real world</em>, do we want an accurate prediction for but can&#8217;t easily measure?</p>

<p><strong>What&#8217;s the circumference of a circle?</strong></p>

<p>Finding pi &#8220;experimentally&#8221; is tough: bust out a string and a ruler?</p>

<p>We can&#8217;t measure a shape with seemingly infinite sides, but we can wonder &#8220;Is there a predicted value for pi that is always accurate as we keep increasing the sides?&#8221;</p>

<p>Archimedes <a href="http://betterexplained.com/articles/prehistoric-calculus-discovering-pi/">figured out</a> that pi had a range of</p>

<p><img src='http://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/31fc9b622525a9d79d4afff1a891db6b.png' width='110.5'height='37' title='\displaystyle{3 \frac{10}{71} &lt; \pi &lt; 3 \frac{1}{7} }' alt='\displaystyle{3 \frac{10}{71} &lt; \pi &lt; 3 \frac{1}{7} }' align=absmiddle class='tex'></p>

<p>using a process like this:</p>

<p><img src="http://betterexplained.com/wp-content/uploads/calculus/pi_polygon.png"></img></p>

<p>It was the precursor to calculus: he determined that pi was a number that stayed between his ever-shrinking boundaries. Nowadays, we have modern <a href="http://functions.wolfram.com/Constants/Pi/09/">limit definitions of pi</a>.</p>

<p><strong>What does perfectly continuous growth look like?</strong></p>

<p>e, one of my <a href="http://betterexplained.com/articles/an-intuitive-guide-to-exponential-functions-e/">favorite numbers</a>, can be defined like this:</p>

<p><img src='http://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/d306e5a95dde600d0106ccf8d63a2805.png' width='153'height='44' title='\displaystyle{e = \lim_{n\to\infty} \left( 1 + \frac{1}{n} \right)^n}' alt='\displaystyle{e = \lim_{n\to\infty} \left( 1 + \frac{1}{n} \right)^n}' align=absmiddle class='tex'></p>

<p><img src="http://betterexplained.com/wp-content/uploads/interest/continuous_growth.png"></img></p>

<p>We can&#8217;t easily measure the result of infinitely-compounded growth. But, if we <em>could make a prediction</em>, is there a single rate that is ever-accurate? It seems to be around 2.71828…</p>

<p><strong>Can we use simple shapes to measure complex ones?</strong></p>

<p>Circles and curves are tough to measure, but rectangles are easy. If we <em>could</em> use an infinite number of rectangles to simulate curved area, can we get a result that withstands infinite scrutiny? (Maybe we can <a href="http://betterexplained.com/articles/a-gentle-introduction-to-learning-calculus/">find the area of a circle</a>.)</p>

<p><img src="http://betterexplained.com/wp-content/uploads/calculus/disc_rings_area.png"></img></p>

<p><strong>Can we find the speed at an instant?</strong></p>

<p>Speed is funny: it needs a before-and-after measurement (distance traveled / time taken), but can&#8217;t we have a speed at individual instants? Hrm.</p>

<p>Limits help answer this conundrum: predict your speed when traveling to a neighboring instant. Then ask the &#8220;impossible question&#8221;: what&#8217;s your predicted speed when the gap to the neighboring instant is zero?</p>

<p>Note: The limit isn&#8217;t a magic cure-all. We can&#8217;t assume one exists, and there may not be an answer to every question. For example: Is the number of integers even or odd? The quantity is infinite, and neither the &#8220;even&#8221; nor &#8220;odd&#8221; prediction stays accurate as we count higher. No well-supported prediction exists.</p>

<p>For pi, e, and the foundations of calculus, smart minds did the proofs to determine that &#8220;Yes, our predicted values get more accurate the closer we look.&#8221; Now I see <em>why</em> limits are so important: they&#8217;re a stamp of approval on our predictions.</p>

<h2>The Math: The Formal Definition Of A Limit</h2>

<p>Limits are well-supported predictions. Here&#8217;s the official definition:</p>

<blockquote>
<img src='http://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/e5f5ada24c028ce96f11dd07d9ac4f92.png' width='102.5'height='25' title='\displaystyle{ \lim_{x \to c}f(x) = L }' alt='\displaystyle{ \lim_{x \to c}f(x) = L }' align=absmiddle class='tex'>

means for all real ε > 0 there exists a real δ > 0 such that for all x with 0 < |x − c| < δ, we have |f(x) − L| < ε
</blockquote>

<p>Let&#8217;s make this readable:</p>

<table width="100%">
<tr><th>Math English</th><th>Human English</th></tr>
<tr><td width="50%">
<div style="float: left; clear: both;">
<img src='http://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/e5f5ada24c028ce96f11dd07d9ac4f92.png' width='102.5'height='25' title='\displaystyle{ \lim_{x \to c}f(x) = L }' alt='\displaystyle{ \lim_{x \to c}f(x) = L }' align=absmiddle class='tex'>
</div>
&nbsp; means
</td>
<td style="vertical-align: top;">When we &#8220;strongly predict&#8221; that f(c) = L, we mean</td></tr>
<tr><td>for all real ε > 0</td><td>for any error margin we want (+/- .1 meters)</td></tr>
<tr><td>there exists a real δ > 0</td><td>there is a zoom level (+/- .1 seconds)</td></tr>
<tr><td>such that for all x with 0 < |x − c| < δ, we have |f(x) − L| < ε</td><td>where the prediction stays accurate to within the error margin</td></tr>
</table>

<p>There&#8217;s a few subtleties here:</p>

<ul>
<li>The zoom level (delta, δ) is the function input, i.e. the time in the video</li>
<li>The error margin (epsilon, ε) is the most the function output (the ball&#8217;s position) can differ from our prediction throughout the entire zoom level</li>
<li>The absolute value condition (0 &lt; |x − c| &lt; δ) means positive and negative offsets must work, and we&#8217;re skipping the black hole itself (when |x &#8211; c| = 0).</li>
</ul>

<p>We can&#8217;t evaluate the black hole input, but we can say &#8220;Except for the missing point, the entire zoom level confirms the prediction <span class="tex-inline" alt="f(c) = L">f(c) = L</span>.&#8221; And because <span class="tex-inline" alt="f(c) = L">f(c) = L</span> holds for <em>any</em> error margin we can find, we feel confident.</p>

<p>Could we have multiple predictions? Imagine we predicted L1 and L2 for f(c). There&#8217;s some difference between them (call it .1), therefore there&#8217;s some error margin (.01) that would reveal the more accurate one. Every function output in the range can&#8217;t be within .01 of both predictions. We either have a single, infinitely-accurate prediction, or we don&#8217;t.</p>

<p>Yes, we can get cute and ask for the &#8220;left hand limit&#8221; (prediction from before the event) and the &#8220;right hand limit&#8221; (prediction from after the event), but we only have a real limit when they agree.</p>

<p>A function is continuous when it always matches the predicted value (and discontinuous if not):</p>

<p><img src='http://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/222b52243f5d74f7e4681bd71a9a6065.png' width='122'height='25' title='\displaystyle{\lim_{x \to c}{f(x)} = f(c)}' alt='\displaystyle{\lim_{x \to c}{f(x)} = f(c)}' align=absmiddle class='tex'></p>

<p>Calculus typically studies continuous functions, playing the game &#8220;We&#8217;re making predictions, but only because we know they&#8217;ll be correct.&#8221;</p>

<h2>The Math: Showing The Limit Exists</h2>

<p>We have the requirements for a solid prediction. Questions asking you to &#8220;Prove the limit exists&#8221; ask you to justify your estimate.</p>

<p>For example: Prove the limit at x=2 exists for</p>

<p><img src='http://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/2d79189a83bd07f6d2470c40a41c4230.png' width='182'height='43' title='\displaystyle{f(x) = \frac{(2x+1)(x-2)}{(x - 2)}}' alt='\displaystyle{f(x) = \frac{(2x+1)(x-2)}{(x - 2)}}' align=absmiddle class='tex'></p>

<p>The first check: do we even need a limit? Unfortunately, we do: just plugging in &#8220;x=2&#8243; means we have a division by zero. Drats.</p>

<p>But intuitively, we see the same &#8220;zero&#8221; (x &#8211; 2) could be cancelled from the top and bottom. Here&#8217;s how to dance this dangerous tango:</p>

<ul>
<li>Assume x is anywhere <em>except</em> 2 (It must be! We&#8217;re making a prediction from the outside.)</li>
<li>We can then cancel (x &#8211; 2) from the top and bottom, since it isn&#8217;t zero.</li>
<li>We&#8217;re left with f(x) = 2x + 1. This function can be used outside the black hole.</li>
<li>What does this simpler function predict? That f(2) = 2*2 + 1 = 5.</li>
</ul>

<p>So f(2) = 5 is our prediction. But did you see the sneakiness? We pretended x wasn&#8217;t 2 [to divide out (x-2)], then plugged in 2 after that troublesome item was gone! Think of it this way: we used the simple behavior from <em>outside the event</em> to predict the gnarly behavior <em>at the event</em>.</p>

<p>We can prove these shenanigans give a solid prediction, and that f(2) = 5 is infinitely accurate.</p>

<p>For any accuracy threshold (ε), we need to find the &#8220;zoom range&#8221; (δ) where we stay within the given accuracy. For example, can we keep the estimate between +/- 1.0?</p>

<p>Sure. We need to find out where</p>

<p><img src='http://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/83058c0e33d044388f94d5a5666bd14c.png' width='121.5'height='19' title='\displaystyle{|f(x) - 5| &lt; 1.0}' alt='\displaystyle{|f(x) - 5| &lt; 1.0}' align=absmiddle class='tex'></p>

<p>so</p>

<p><img src='http://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/38e5f9f25da145aefa3aa8ac4945473b.png' width='136.5'height='129' title='&#13;&#10;\begin{align*}&#13;&#10;|2x + 1 - 5| &amp;&lt; 1.0 \\&#13;&#10;|2x - 4| &amp;&lt; 1.0 \\&#13;&#10;|2(x - 2)| &amp;&lt; 1.0 \\&#13;&#10;2|(x - 2)| &amp;&lt; 1.0 \\&#13;&#10;|x - 2| &amp;&lt; 0.5&#13;&#10;\end{align*}&#13;&#10;' alt='&#13;&#10;\begin{align*}&#13;&#10;|2x + 1 - 5| &amp;&lt; 1.0 \\&#13;&#10;|2x - 4| &amp;&lt; 1.0 \\&#13;&#10;|2(x - 2)| &amp;&lt; 1.0 \\&#13;&#10;2|(x - 2)| &amp;&lt; 1.0 \\&#13;&#10;|x - 2| &amp;&lt; 0.5&#13;&#10;\end{align*}&#13;&#10;' align=absmiddle class='tex'></p>

<p>In other words, x must stay within 0.5 of 2 to maintain the initial accuracy requirement of 1.0. Indeed, when x is between 1.5 and 2.5, f(x) goes from f(1.5) = 4 to and f(2.5) = 6, staying +/- 1.0 from our predicted value of 5.</p>

<p>We can generalize to any error tolerance (ε) by plugging it in for 1.0 above. We get:</p>

<p><img src='http://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/193f1e0d5cceb586cabeb6a025c93bba.png' width='117.5'height='19' title='\displaystyle{|x - 2| &lt; 0.5 \cdot \epsilon}' alt='\displaystyle{|x - 2| &lt; 0.5 \cdot \epsilon}' align=absmiddle class='tex'></p>

<p>If our zoom level is &#8220;δ = 0.5 * ε&#8221;, we&#8217;ll stay within the original error. If our error is 1.0 we need to zoom to .5; if it&#8217;s 0.1, we need to zoom to 0.05.</p>

<p>This simple function was a convenient example. The idea is to start with the initial constraint (|f(x) &#8211; L| &lt; ε), plug in f(x) and L, and solve for the distance away from the black-hole point (|x &#8211; c| &lt; ?). It&#8217;s often an exercise in algebra.</p>

<p>Sometimes you&#8217;re asked to simply find the limit (plug in 2 and get f(2) = 5), other times you&#8217;re asked to prove a limit exists, i.e. crank through the epsilon-delta algebra.</p>

<h2>Flipping Zero and Infinity</h2>

<p>Infinity, when used in a limit, means &#8220;grows without stopping&#8221;. The symbol &#8734; is no more a number than the sentence &#8220;grows without stopping&#8221; or &#8220;my supply of underpants is dwindling&#8221;. They are concepts, not numbers (for our level of math, <a href="http://en.wikipedia.org/wiki/Aleph_number">Aleph</a> me alone).</p>

<p>When using &#8734; in a limit, we&#8217;re asking: &#8220;As x grows without stopping, can we make a prediction that remains accurate?&#8221;. If there is a limit, it means the predicted value is always confirmed, no matter how far out we look.</p>

<p>But, I still don&#8217;t like infinity because I can&#8217;t see it. But I can see zero. With limits, you can rewrite</p>

<p><img src='http://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/26e6dab1aeb0d5deb4a6bcb62ce4c47f.png' width='35.5'height='24' title='\displaystyle{\lim_{x \to \infty}}' alt='\displaystyle{\lim_{x \to \infty}}' align=absmiddle class='tex'></p>

<p>as</p>

<p><img src='http://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/8b08b65350f6d64b6d0a691f585a5748.png' width='29.5'height='32.5' title='\displaystyle{\lim_{\frac{1}{x} \to 0}}' alt='\displaystyle{\lim_{\frac{1}{x} \to 0}}' align=absmiddle class='tex'></p>

<p>You can get sneaky and define y = 1/x, replace items in your formula, and then use</p>

<p><img src='http://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/c9e82eb21b50b1c426425f2994988f1c.png' width='28'height='26.5' title='\displaystyle{\lim_{y \to 0}}' alt='\displaystyle{\lim_{y \to 0}}' align=absmiddle class='tex'></p>

<p>so it looks like a normal problem again! I prefer this arrangement, because I can see the location we&#8217;re narrowing in on (we&#8217;re always running out of paper when charting the infinite version).</p>

<h2>Why Aren&#8217;t Limits Used More Often?</h2>

<p>Imagine a kid who figured out that &#8220;Putting a zero on the end&#8221; made a number 10x larger. Have 5? Write down &#8220;5&#8243; then &#8220;0&#8243; or 50. Have 100? Make it 1000. And so on.</p>

<p>He didn&#8217;t figure out why multiplication works, why this rule is justified… but, you&#8217;ve gotta admit, he sure can multiply by 10. Sure, there are some edge cases (Would 0 become &#8220;00&#8243;?), but it works pretty well.</p>

<p>The rules of calculus were discovered informally (by modern standards). Newton deduced that &#8220;The derivative of x^3 is 3x^2&#8243; without rigorous justification. Yet engines whirl and airplanes fly based on his unofficial results.</p>

<p>The calculus pedagogy mistake is creating a roadblock like &#8220;You must know Limits™ before appreciating calculus&#8221;, when it&#8217;s clear the inventors of calculus didn&#8217;t. I&#8217;d prefer this progression:</p>

<ul>
<li>Calculus asks seemingly impossible questions: When can rectangles measure a curve? Can we detect instantaneous change?</li>
<li>Limits give a strategy for answering &#8220;impossible&#8221; questions (&#8220;If you can make a prediction that withstands infinite scrutiny, we&#8217;ll say it&#8217;s ok.&#8221;)</li>
<li>They&#8217;re a great tag-team: Calculus explores, limits verify. We memorize shortcuts for the results we verified with limits (d/dx x^3 = 3x^2), just like we memorize shortcuts for the rules we verified with multiplication (adding a zero means times 10). But it&#8217;s still nice to know why the shortcuts are justified.</li>
</ul>

<p>Limits aren&#8217;t the only tool for checking the answers to impossible questions; infinitesimals work too. The key is understanding <em>what</em> we&#8217;re trying to predict, <em>then</em> learning the rules of making predictions.</p>

<p>Happy math.</p>
]]></content:encoded>
			<wfw:commentRss>http://betterexplained.com/articles/an-intuitive-introduction-to-limits/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Understanding Bayes Theorem With Ratios</title>
		<link>http://betterexplained.com/articles/understanding-bayes-theorem-with-ratios/</link>
		<comments>http://betterexplained.com/articles/understanding-bayes-theorem-with-ratios/#comments</comments>
		<pubDate>Fri, 01 Mar 2013 19:50:07 +0000</pubDate>
		<dc:creator>kalid</dc:creator>
				<category><![CDATA[Math]]></category>

		<guid isPermaLink="false">http://betterexplained.com/?p=2939</guid>
		<description><![CDATA[My <a href="http://betterexplained.com/articles/an-intuitive-and-short-explanation-of-bayes-theorem/">first intuition&#8230; <a href="http://betterexplained.com/articles/understanding-bayes-theorem-with-ratios/" class="read_more">Read article</a></a> about Bayes Theorem was &#8220;take evidence and account for false positives&#8221;. Does a lab result mean you&#8217;re sick? Well, how rare is the disease, and how often do healthy people test positive? Misleading signals must be considered.]]></description>
				<content:encoded><![CDATA[<p>My <a href="http://betterexplained.com/articles/an-intuitive-and-short-explanation-of-bayes-theorem/">first intuition</a> about Bayes Theorem was &#8220;take evidence and account for false positives&#8221;. Does a lab result mean you&#8217;re sick? Well, how rare is the disease, and how often do healthy people test positive? Misleading signals must be considered.</p>

<p>This helped me muddle through practice problems, but I couldn&#8217;t <em>think</em> with Bayes. The big obstacles:</p>

<p><strong>Percentages are hard to reason with.</strong> Odds compare the relative frequency of scenarios (A:B) while percentages use a part-to-whole &#8220;global scenario&#8221; [A/(A+B)]. A coin has equal odds (1:1) or a 50% chance of heads. Great. What happens when heads are 18x more likely? Well, the odds are 18:1, can you rattle off the decimal percentage? (I&#8217;ll wait…) Odds require less computation, so let&#8217;s start with them.</p>

<p><strong>Equations miss the big picture.</strong> Here&#8217;s Bayes Theorem, as typically presented:</p>

<p><img src='http://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/70046d4ee153ca74d961892dd70705c8.png' width='390.5'height='44' title='\displaystyle{\displaystyle{\Pr(\mathrm{A}|\mathrm{X}) = \frac{\Pr(\mathrm{X}|\mathrm{A})\Pr(\mathrm{A})}{\Pr(\mathrm{X|A})\Pr(A)+ \Pr(\mathrm{X|\sim A})\Pr(\sim A)}}}' alt='\displaystyle{\displaystyle{\Pr(\mathrm{A}|\mathrm{X}) = \frac{\Pr(\mathrm{X}|\mathrm{A})\Pr(\mathrm{A})}{\Pr(\mathrm{X|A})\Pr(A)+ \Pr(\mathrm{X|\sim A})\Pr(\sim A)}}}' align=absmiddle class='tex'></p>

<p>It reads right-to-left, with a mess of conditional probabilities. How about this version:</p>

<pre><code>original odds * evidence adjustment = new odds
</code></pre>

<p>Bayes is about starting with a guess (1:3 odds for rain:sunshine), taking evidence (it&#8217;s July in the Sahara, sunshine 1000x more likely), and updating your guess (1:3000 chance of rain:sunshine). The &#8220;evidence adjustment&#8221; is how much better, or worse, we feel about our odds now that we have extra information (if it was December in Seattle, you might say rain was 1000x as likely).</p>

<p>Let&#8217;s start with ratios and sneak up to the complex version.</p>

<h2>Caveman Statistician Og</h2>

<p>Og just finished his CaveD program, and runs statistical research for his tribe:</p>

<ul>
<li>He saw 50 deer and 5 bears overall (50:5 odds)</li>
<li>At night, he saw 10 deer and 4 bears (10:4 odds)</li>
</ul>

<p>What can he deduce? Well, </p>

<pre><code>original odds * evidence adjustment = new odds
</code></pre>

<p>or</p>

<pre><code>evidence adjustment = new odds / original odds
</code></pre>

<p>At night, he realizes deer are 1/4 as likely as they were previously:</p>

<pre><code>10:4 / 50:5 = 2.5 / 10 = 1/4
</code></pre>

<p>(Put another way, bears are 4x as likely at night)</p>

<p>Let&#8217;s cover ratios a bit. A:B describes how much A we get for every B (imagine miles per gallon as the ratio miles:gallon). Compare values with division: going from 25:1 to 50:1 means you doubled your efficiency (50/25 = 2). Similarly, we just discovered how our &#8220;deers per bear&#8221; amount changed.</p>

<p>Og happily continues his research:</p>

<ul>
<li>By the river, bears are 20x more likely (he saw 2 deer and 4 bears, so 2:4 / 50:5 = 1:20)</li>
<li>In winter, deer are 3x as likely (30 deer and 1 bear, 30:1 / 50:5 = 3:1)</li>
</ul>

<p>He takes a scenario, compares it to the baseline, and computes the evidence adjustment.</p>

<p>Caveman Clarence subscribes to Og&#8217;s journal, and wants to apply the findings to his forest (where deer:bears are 25:1). Suppose Clarence hears an animal approaching:</p>

<ul>
<li>His general estimate is 25:1 odds of deer:bear</li>
<li>It&#8217;s at night, with bears 4x as likely => 25:4</li>
<li>It&#8217;s by the river, with bears 20x as likely => 25:80</li>
<li>It&#8217;s in the winter, with deer 3x more likely => 75:80</li>
</ul>

<p>Clarence guesses &#8220;bear&#8221; with near-even odds (75:80) and tiptoes out of there.</p>

<p>That&#8217;s Bayes. In fancy language:</p>

<ul>
<li>Start with a prior probability, the general odds before evidence</li>
<li>Collect evidence, and determine how much it changes the odds</li>
<li>Compute the posterior probability, the odds after updating</li>
</ul>

<h2>Bayesian Spam Filter</h2>

<p>Let&#8217;s build a <a href="http://www.paulgraham.com/spam.html">spam filter</a> based on Og&#8217;s Bayesian Bear Detector.</p>

<p>First, grab a collection of regular and spam email. Record how often a word appears in each:</p>

<pre><code>             spam      normal
hello          3         3
darling        1         5
buy            3         2
viagra         3         0
...
</code></pre>

<p>(&#8220;hello&#8221; appears equally, but &#8220;buy&#8221; skews toward spam)</p>

<p>We compute odds just like before. Let&#8217;s assume incoming email has 9:1 chance of spam, and we see &#8220;hello darling&#8221;:</p>

<ul>
<li>A generic message has 9:1 odds of spam:regular</li>
<li>Adjust for &#8220;hello&#8221; => keep the 9:1 odds (&#8220;hello&#8221; is equally-likely in both sets)</li>
<li>Adjust for &#8220;darling&#8221; => 9:5 odds (&#8220;darling&#8221; appears 5x as often in normal emails)</li>
<li>Final chances => 9:5 odds of spam</li>
</ul>

<p>We&#8217;re learning towards spam (9:5 odds). However, it&#8217;s less spammy than our starting odds (9:1), so we let it through.</p>

<p>Now consider a message like &#8220;buy viagra&#8221;:</p>

<ul>
<li>Prior belief: 9:1 chance of spam</li>
<li>Adjust for &#8220;buy&#8221;: 27:2 (3:2 adjustment towards spam)</li>
<li>Adjust for (&#8220;viagra&#8221;): …uh oh!</li>
</ul>

<p>&#8220;Viagra&#8221; never appeared in a normal message. Is it a guarantee of spam?</p>

<p>Probably not: we should intelligently adjust for new evidence. Let&#8217;s assume there&#8217;s a regular email, somewhere, with that word, and make the &#8220;viagra&#8221; odds 3:1. Our chances become 27:2 * 3:1 = 81:2.</p>

<p>Now we&#8217;re geting somewhere! Our initial 9:1 guess shifts to 81:2. Now is it spam?</p>

<p>Well, how horrible is a false positive?</p>

<p>81:2 odds imply for every 81 spam messages like this, we&#8217;ll incorrectly block 2 normal emails. That ratio might be too painful. With more evidence (more words or other characteristics), we might wait for 1000:1 odds before calling a message spam.</p>

<h2>Exploring Bayes Theorem</h2>

<p>We can check our intuition by seeing if we naturally ask leading questions:</p>

<ul>
<li><p><strong>Is evidence truly independent?</strong> Are there links between animal behavior at night and in the winter, or words that appear together? Sure. We &#8220;naively&#8221; assume evidence is independent (and yet, in our bumbling, create effective filters anyway).</p></li>
<li><p><strong>How much evidence is enough?</strong> Is seeing 2 deer &#038; 1 bear the same 2:1 evidence adjustment as 200 deer and 100 bears?</p></li>
<li><p><strong>How accurate were the starting odds in the first place?</strong> Prior beliefs change everything. (&#8220;A Bayesian is one who, vaguely expecting a horse, and catching a glimpse of a donkey, strongly believes he has seen a mule.&#8221;)</p></li>
<li><p><strong>Do absolute probabilities matter?</strong> We usually need the most-likely theory (&#8220;Deer or bear?&#8221;), not the global chance of this scenario (&#8220;What&#8217;s the probability of deers at night in the winter by the river vs. bears at night in the winter by the river?&#8221;). Many Bayesian calculations ignore the global probabilities, which cancel when dividing, and essentially use an odds-centric approach.</p></li>
<li><p><strong>Can our filter be tricked?</strong> A spam message might add chunks of normal text to appear innocuous and &#8220;poison&#8221; the filter. You&#8217;ve probably seen this yourself.</p></li>
<li><p><strong>What evidence should we use?</strong> Let the data speak. Email might have dozens of characteristics (time of day, message headers, country of origin, HTML tags…). Give every characteristic a likelihood factor and let Bayes sort &#8216;em out.</p></li>
</ul>

<h2>Thinking With Ratios and Percentages</h2>

<p>The ratio and percentage approaches ask slightly different questions:</p>

<p><strong>Ratios:</strong> Given the odds of each outcome, how does evidence adjust them?</p>

<p><img src="http://betterexplained.com/wp-content/uploads/math/bayes/bayes_as_ratio.png" width="500"></img></p>

<p>The evidence adjustment just skews the initial odds, piece-by-piece.</p>

<p><strong>Percentages:</strong> What is the chance of an outcome after supporting evidence is found?</p>

<p><img src="http://betterexplained.com/wp-content/uploads/math/bayes/bayes_as_percent.png" width="500"></img></p>

<p>In the percentage case,</p>

<ul>
<li>&#8220;% Bears&#8221; is the overall chance of a bear appearing anywhere</li>
<li>&#8220;% Bears Going to River&#8221; is how likely a bear is to trigger the &#8220;river&#8221; data point</li>
<li>&#8220;% Bear at River&#8221; is the combined chance of having a bear, and it going to the river. In stats terms, <code>P(event and evidence) = P(event) * P(event implies evidence) = P(event) * P(evidence|event)</code>. I see conditional probabilities as &#8220;Chances that X implies Y&#8221; not the twisted &#8220;Chances of Y, given X happened&#8221;. </li>
</ul>

<p>Let&#8217;s redo the original <a href="http://betterexplained.com/articles/an-intuitive-and-short-explanation-of-bayes-theorem/">cancer example</a>:</p>

<ul>
<li>1% of the population has cancer</li>
<li>9.6% of healthy people test positive, 80% of people with cancer do</li>
</ul>

<p>If you see a positive result, what&#8217;s the chance of cancer?</p>

<p><strong>Ratio Approach:</strong></p>

<ul>
<li>Cancer:Healthy ratio is 1:99</li>
<li>Evidence adjustment: 80/100 : 9.6/100 = 80:9.6 (80% of sick people are &#8220;at the river&#8221;, and 9.6% of healthy people are).</li>
<li>Final odds: 1:99 * 80:9.6 = 80:950.4 (roughly 1:12 odds of cancer, ~7.7% chance)</li>
</ul>

<p>The intuition: the initial 1:99 odds are pretty skewed. Even with a 8.3x (80:9.6) boost from a positive test result, cancer remains unlikely.</p>

<p><strong>Percentage Approach:</strong></p>

<ul>
<li>Cancer chance is 1%</li>
<li>Chance of true positive = 1% * 80% = .008</li>
<li>Chance of false positive = 99% * 9.6% = .09504</li>
<li>Chance of having cancer = .008 / (.008 + .09504) = 7.7%</li>
</ul>

<p>When written with percentages, we start from <em>absolute</em> chances. There&#8217;s a global 0.8% chance of finding a sick patient with a positive result, and a global 9.504% chance of a healthy patient with a positive result. We then compute the chance these global percentages indicate something useful.</p>

<p>Let the approaches be complements: percentages for a bird&#8217;s-eye view, and ratios for seeing how individual odds are adjusted. We&#8217;ll save the myriad other interpretations for another day.</p>

<p>Happy math.</p>
]]></content:encoded>
			<wfw:commentRss>http://betterexplained.com/articles/understanding-bayes-theorem-with-ratios/feed/</wfw:commentRss>
		<slash:comments>34</slash:comments>
		</item>
		<item>
		<title>An Interactive Guide To The Fourier Transform</title>
		<link>http://betterexplained.com/articles/an-interactive-guide-to-the-fourier-transform/</link>
		<comments>http://betterexplained.com/articles/an-interactive-guide-to-the-fourier-transform/#comments</comments>
		<pubDate>Thu, 20 Dec 2012 11:30:10 +0000</pubDate>
		<dc:creator>kalid</dc:creator>
				<category><![CDATA[Math]]></category>

		<guid isPermaLink="false">http://betterexplained.com/?p=2851</guid>
		<description><![CDATA[The Fourier Transform is one of deepest insights ever made. Unfortunately, the meaning is buried within dense equations:





Yikes. Rather than deciphering it symbol-by-symbol, let's experience the idea. Here's a plain-English metaphor:

<ul>
<li><strong>What does the Fourier Transform do?</strong> Given a </li>&#8230; <a href="http://betterexplained.com/articles/an-interactive-guide-to-the-fourier-transform/" class="read_more">Read article</a></ul>]]></description>
				<content:encoded><![CDATA[<p>The Fourier Transform is one of deepest insights ever made. Unfortunately, the meaning is buried within dense equations:</p>

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

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

<p>Yikes. Rather than deciphering it symbol-by-symbol, let's experience the idea. 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>Next, we'll refine the analogy into "math-English":</p>

<ul>
<li>The Fourier Transform extracts each "cycle ingredient" from a time-based signal (the cycle strength, delay &#038; speed), resulting in a final "cycle recipe"</li>
</ul>

<p>Time for the equations? No! Let's get our hands dirty and <em>experience</em> cycles making patterns 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>

<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 "What did I see" into "How was it made?".</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 src="http://betterexplained.com/wp-content/uploads/images/smoothie-to-recipe-20121030-223058.png" height="300"></img></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 last 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 behave the same (<a href="http://betterexplained.com/articles/linear-algebra-guide/">linearly</a>).</p></li>
</ul>

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

<p>The Fourier Transform takes a specific viewpoint: <strong>What if any signal could be made from circular motion (repeating cycles)?</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 intution.</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 &#038; strengths), 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 Charlier 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="http://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="http://betterexplained.com/articles/intuitive-understanding-of-eulers-formula/">Euler's formula</a> is a clever way to generate one:</p>

<p><img src="http://betterexplained.com/wp-content/uploads/euler/equal_paths.png" alt="euler path" /></p>

<p>Must we use imaginary exponents to move in a circle? Nope. But it's convenient and compact. We <em>can</em> separate the path into real and imaginary parts, but don't forget the big picture: we move in circles.</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 circular path 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 be at the same spot: starting point + amount traveled = 45 + 180 = 225 degrees (on a 2-inch circle).</p>

<p><img src="http://betterexplained.com/wp-content/uploads/images//circular-path-parameters-20121201-203317.png" width="500"></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="http://betterexplained.com/examples/fourier/?cycles=0,1" frameborder=0 width="550px" height="280px"></iframe>

<p>(Layout and initial code based on <a href="http://treeblurb.com/dev_math/sin_canv00.html">this animation</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 strength for the 0Hz cycle (0Hz = a constant cycle, stuck on the x-axis at zero degrees)</li>
<li>1 strength 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 strength 1, 2Hz of strength 1":</p>

<iframe src="http://betterexplained.com/examples/fourier/?cycles=0,1,1" frameborder=0 width="550px" height="280px"></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 1Hz cycle that starts at 45 degrees:</p>

<iframe src="http://betterexplained.com/examples/fourier/?cycles=0,1:45" frameborder=0 width="550px" height="280px"></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, strengths 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="http://betterexplained.com/wp-content/uploads/images//time-patterns-20121205-164541.png" target="_blank">
<img src="http://betterexplained.com/wp-content/uploads/images//time-patterns-20121205-164541.png" width="500px"></img></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 parens for time points)</p>

<p>Although the spike seems boring to us time-dwellers (<em>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 &#038; South, East &#038; 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 the 3Hz cycle starts at 0, gets to position 3, then position "6" (with only 4 positions, 6 <a href="http://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 &#038; 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 znd 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 time spikes: <code>(2 0)</code>, <code>(3 0 0)</code>, <code>(4 0 0 0)</code>).</p>

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

<p><img src="http://betterexplained.com/wp-content/uploads/images/fourier-interference-20121211-171719.png" width="400px"></img></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 alread 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 src="http://betterexplained.com/wp-content/uploads/images/delayed-spike-20121214-162623.png" width="400px"></img></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 strength 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 src="http://betterexplained.com/wp-content/uploads/images/fourier-explained-20121219-224649.png" width="500px"></img></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 1/sqrt(N) on both transforms (going forward and back still has 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 &#038; 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://blog.brokenrobotllc.com/">Shaheen Gandhi</a>, Roger Cheng, and <a href="http://britcruise.com/">Brit Cruise</a> for kicking around ideas &#038; 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="http://www.altdevblogaday.com/2011/05/17/understanding-the-fourier-transform/">great interpreation</a> of the Fourier Transform:</p>

<p><img src="http://betterexplained.com/wp-content/uploads/images/DerivedDFT.png"></img></p>

<p>(With an <a href="http://fixplz.blourp.com/blog/=dfts">animation here</a>)</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 needs a negative sign). 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="http://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>

<iframe src="http://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 strength of 1 for every component (press Enter after inputting each number). Fun fact: with enough terms, you can draw any shape, even <a href="http://www.youtube.com/watch?v=QVuU2YCwHjw&#038;feature=youtu.be">Homer Simpson</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://betterexplained.com/articles/an-interactive-guide-to-the-fourier-transform/feed/</wfw:commentRss>
		<slash:comments>98</slash:comments>
		</item>
		<item>
		<title>An Intuitive Guide to Linear Algebra</title>
		<link>http://betterexplained.com/articles/linear-algebra-guide/</link>
		<comments>http://betterexplained.com/articles/linear-algebra-guide/#comments</comments>
		<pubDate>Tue, 09 Oct 2012 14:36:36 +0000</pubDate>
		<dc:creator>kalid</dc:creator>
				<category><![CDATA[Math]]></category>

		<guid isPermaLink="false">http://betterexplained.com/?p=2763</guid>
		<description><![CDATA[Despite two linear algebra classes, my knowledge consisted of &#8220;Matrices, determinants, eigen something something&#8221;.

Why? Well, let&#8217;s try this course format:

<ul>
<li>Name the course &#8220;Linear Algebra&#8221; but focus on things called matrices and vectors</li>
<li>Label items with similar-looking letters (i/j), </li>&#8230; <a href="http://betterexplained.com/articles/linear-algebra-guide/" class="read_more">Read article</a></ul>]]></description>
				<content:encoded><![CDATA[<p>Despite two linear algebra classes, my knowledge consisted of &#8220;Matrices, determinants, eigen something something&#8221;.</p>

<p>Why? Well, let&#8217;s try this course format:</p>

<ul>
<li>Name the course &#8220;Linear Algebra&#8221; but focus on things called matrices and vectors</li>
<li>Label items with similar-looking letters (i/j), and even better, similar-looking-and-sounding ones (m/n)</li>
<li>Teach concepts like Row/Column order with mnemonics instead of explaining the reasoning</li>
<li>Favor abstract examples (2d vectors! 3d vectors!) and avoid real-world topics until the final week</li>
</ul>

<p>The survivors are physicists, graphics programmers and other masochists. We missed the key insight:</p>

<p><strong>Linear algebra gives you mini-spreadsheets for your math equations.</strong></p>

<p>We can take a table of data (a matrix) and create updated tables from the original. It&#8217;s the power of a spreadsheet written as an equation.</p>

<p>Here&#8217;s the linear algebra introduction I wish I had, with a real-world stock market example.</p>

<h2>What&#8217;s in a name?</h2>

<p>&#8220;Algebra&#8221; means, roughly, &#8220;relationships&#8221;. Grade-school algebra explores the relationship between unknown numbers. Without knowing x and y, we can still work out that (x + y)^2 = x^2 + 2xy + y^2.</p>

<p>&#8220;Linear Algebra&#8221; means, roughly, &#8220;line-like relationships&#8221;. Let&#8217;s clarify a bit.</p>

<p>Straight lines are predictable. Imagine a rooftop: move forward 3 horizontal feet (relative to the ground) and you might rise 1 foot in elevation (The slope! Rise/run = 1/3). Move forward 6 feet, and you&#8217;d expect a rise of 2 feet. Contrast this with climbing a dome: each horizontal foot forward raises you a different amount.</p>

<p>Lines are nice and predictable:</p>

<ul>
<li>If 3 feet forward has a 1-foot rise, then going 10x as far should give a 10x rise (30 feet forward is a 10-foot rise)</li>
<li>If 3 feet forward has a 1-foot rise, and 6 feet has a 2-foot rise, then (3 + 6) feet should have a (1 + 2) foot rise</li>
</ul>

<p>In math terms, an operation F is linear if scaling inputs scales the output, and adding inputs adds the outputs:</p>

<p><img src='http://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/04ee0a25c7bbdf817f620334f738f1c9.png' width='191'height='45.5' title='&#13;&#10;\begin{align*}&#13;&#10;F(ax) &amp;= a \cdot F(x) \\&#13;&#10;F(x + y) &amp;= F(x) + F(y)&#13;&#10;\end{align*}&#13;&#10;' alt='&#13;&#10;\begin{align*}&#13;&#10;F(ax) &amp;= a \cdot F(x) \\&#13;&#10;F(x + y) &amp;= F(x) + F(y)&#13;&#10;\end{align*}&#13;&#10;' align=absmiddle class='tex'></p>

<p>In our example, F(x) calculates the rise when moving forward x feet. F(10*3) = 10 * F(3) = 10 and F(3+6) = F(3) + F(6) = 3.</p>

<h2>Linear Operations</h2>

<p>An operation is a calculation based on some inputs. Which operations are linear and predictable? Multiplication, it seems.</p>

<p>Exponents (F(x) = x^2) aren&#8217;t predictable: 10^2 is 100, but 20^2 is 400. We doubled the input but quadrupled the output.</p>

<p>Surprisingly, regular addition isn&#8217;t linear either. Consider the &#8220;add three&#8221; function:</p>

<p><img src='http://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/f72cd045fad45fb14076ddb9c2e205ad.png' width='111'height='73' title='&#13;&#10;\begin{align*}&#13;&#10;F(x) &amp;= x + 3 \\&#13;&#10;F(10) &amp;= 13 \\&#13;&#10;F(20) &amp;= 23&#13;&#10;\end{align*}&#13;&#10;' alt='&#13;&#10;\begin{align*}&#13;&#10;F(x) &amp;= x + 3 \\&#13;&#10;F(10) &amp;= 13 \\&#13;&#10;F(20) &amp;= 23&#13;&#10;\end{align*}&#13;&#10;' align=absmiddle class='tex'></p>

<p>We doubled the input and did not double the output. (Yes, F(x) = x + 3 happens to be the equation for an <em>offset</em> line, but it&#8217;s still not &#8220;linear&#8221; because F(10) isn&#8217;t 10 * F(1). Fun.)</p>

<p>Our only hope is to multiply by a constant: F(x) = ax (in our roof example, a=1/3). However, we can still combine linear operations to make a new linear operation:</p>

<p><img src='http://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/663b402add9abb5256c58b00730025d4.png' width='380.5'height='18' title='\displaystyle{G(x, y, z) = F(x + y + z) = F(x) + F(y) + F(z)}' alt='\displaystyle{G(x, y, z) = F(x + y + z) = F(x) + F(y) + F(z)}' align=absmiddle class='tex'></p>

<p>G is made of 3 linear subpieces: if we double the inputs, we&#8217;ll double the output.</p>

<p>We have &#8220;mini arithmetic&#8221;: multiply inputs by a constant, and add the results. It&#8217;s actually useful because we can split inputs apart, analyze them individually, and combine the results:</p>

<p><img src='http://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/aaa2d86705d06b750e305ccacd68ce74.png' width='357'height='18' title='\displaystyle{G(x,y,z) = G(x,0,0) + G(0,y,0) + G(0,0,z)}' alt='\displaystyle{G(x,y,z) = G(x,0,0) + G(0,y,0) + G(0,0,z)}' align=absmiddle class='tex'></p>

<p>If the inputs interacted like exponents, we couldn&#8217;t separate them &#8212; we&#8217;d have to analyze everything at once.</p>

<h2>Organizing Inputs and Operations</h2>

<p>Most courses hit you in the face with the details of a matrix. &#8220;Ok kids, let&#8217;s learn to speak. Select a subject, verb and object. Next, conjugate the verb. Then, add the prepositions&#8230;&#8221;</p>

<p><strong>No!</strong> Grammar is not the focus. What&#8217;s the key idea?</p>

<ul>
<li>We have a bunch of inputs to track</li>
<li>We have predictable, linear operations to perform (our &#8220;mini-arithmetic&#8221;)</li>
<li>We generate a result, perhaps transforming it again</li>
</ul>

<p>Ok. First, how should we track a bunch of inputs? How about a list:</p>

<pre><code>x
y
z
</code></pre>

<p>Not bad. We could write it (x, y, z) too &#8212; hang onto that thought.</p>

<p>Next, how should we track our operations? Remember, we only have &#8220;mini arithmetic&#8221;: multiplications, with a final addition. If our operation F behaves like this:</p>

<p><img src='http://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/0e14e1462e4d71e33254bca3034f93f6.png' width='197.5'height='18' title='\displaystyle{F(x, y, z) = 3x + 4y + 5z}' alt='\displaystyle{F(x, y, z) = 3x + 4y + 5z}' align=absmiddle class='tex'></p>

<p>We could abbreviate the entire function as (3, 4, 5). We know to multiply the first input by the first value, the second input by the second value, etc.,  and add the result.</p>

<p>Only need the first input?</p>

<p><img src='http://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/7df6fe52f03a79f5d43aa7c581e741a4.png' width='278'height='18' title='\displaystyle{G(x, y, z) = 3x + 0y + 0z = (3, 0, 0)}' alt='\displaystyle{G(x, y, z) = 3x + 0y + 0z = (3, 0, 0)}' align=absmiddle class='tex'></p>

<p>Let&#8217;s spice it up: how should we handle multiple sets of inputs? Let&#8217;s say we want to run operation F on both (a, b, c) and (x, y, z). We could try this:</p>

<p><img src='http://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/366129689a962a39d13fc8bba305e1b4.png' width='149.5'height='18' title='\displaystyle{F(a, b, c, x, y, z) = ?}' alt='\displaystyle{F(a, b, c, x, y, z) = ?}' align=absmiddle class='tex'></p>

<p>But it won&#8217;t work: F expects 3 inputs, not 6. We should separate the inputs into groups:</p>

<pre><code>1st Input  2nd Input
--------------------
a          x
b          y
c          z
</code></pre>

<p>Much neater.</p>

<p>And how could we run the same input through several operations? Have a row for each operation:</p>

<pre><code>F: 3 4 5
G: 3 0 0
</code></pre>

<p>Neat. We&#8217;re getting organized: inputs in vertical columns, operations in horizontal rows.</p>

<h2>Visualizing The Matrix</h2>

<p>Words aren&#8217;t enough. Here&#8217;s how I visualize inputs, operations, and outputs:</p>

<p><img src="http://betterexplained.com/wp-content/uploads/images//linear-algebra-visualize-20121002-221620.png" alt="linear algebra reference" /></p>

<p>Imagine &#8220;pouring&#8221; each input along each operation:</p>

<p><img src="http://betterexplained.com/wp-content/uploads/images//linear-algebra-pour-20121002-220550.png" alt="linear algebra pour in" /></p>

<p>As an input passes an operation, it creates an output item. In our example, the input (a, b, c) goes against operation F and outputs 3a + 4b + 5c. It goes against operation G and outputs 3a + 0 + 0.</p>

<p>Time for the red pill. A matrix is a shorthand for our diagrams:</p>

<p><img src='http://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/3aa4f8c19764f6aed0969bee9b27bd57.png' width='333.5'height='66' title='\text{I}\text{nputs} = A = \begin{bmatrix} \text{i}\text{nput1}&amp;\text{i}\text{nput2}\end{bmatrix} = \begin{bmatrix}a &amp; x\\b &amp; y\\c &amp; z\end{bmatrix}' alt='\text{I}\text{nputs} = A = \begin{bmatrix} \text{i}\text{nput1}&amp;\text{i}\text{nput2}\end{bmatrix} = \begin{bmatrix}a &amp; x\\b &amp; y\\c &amp; z\end{bmatrix}' align=absmiddle class='tex'></p>

<p><img src='http://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/b6326fd70b2a885f537f6d96a1802b9d.png' width='361'height='44' title='\text{Operations} = M = \begin{bmatrix}\text{operation1}\\ \text{operation2}\end{bmatrix} = \begin{bmatrix}3 &amp; 4 &amp; 5\\3 &amp; 0 &amp; 0\end{bmatrix}' alt='\text{Operations} = M = \begin{bmatrix}\text{operation1}\\ \text{operation2}\end{bmatrix} = \begin{bmatrix}3 &amp; 4 &amp; 5\\3 &amp; 0 &amp; 0\end{bmatrix}' align=absmiddle class='tex'></p>

<p>A matrix is a single variable representing a spreadsheet of inputs or operations.</p>

<p><strong>Trickiness #1: The reading order</strong></p>

<p>Instead of an input => matrix => output flow, we use function notation, like y = f(x) or f(x) = y. We usually write a matrix with a capital letter (F), and a single input column with lowercase (x). Because we have several inputs (A) and outputs (B), they&#8217;re considered matrices too:</p>

<p><img src='http://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/175ec48c2ca59b2f32e22b646e2cb1c7.png' width='71'height='13' title='\displaystyle{MA = B}' alt='\displaystyle{MA = B}' align=absmiddle class='tex'></p>

<p><img src='http://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/428b077f3e094146c651866a0619bbd4.png' width='397.5'height='66' title='&#13;&#10;\begin{bmatrix}3 &amp; 4 &amp; 5\\3 &amp; 0 &amp; 0\end{bmatrix} \begin{bmatrix}a &amp; x\\b &amp; y\\c &amp; z\end{bmatrix}&#13;&#10;= \begin{bmatrix}3a + 4b + 5c &amp; 3x + 4y + 5z\\ 3a &amp; 3x\end{bmatrix}&#13;&#10;' alt='&#13;&#10;\begin{bmatrix}3 &amp; 4 &amp; 5\\3 &amp; 0 &amp; 0\end{bmatrix} \begin{bmatrix}a &amp; x\\b &amp; y\\c &amp; z\end{bmatrix}&#13;&#10;= \begin{bmatrix}3a + 4b + 5c &amp; 3x + 4y + 5z\\ 3a &amp; 3x\end{bmatrix}&#13;&#10;' align=absmiddle class='tex'></p>

<p><strong>Trickiness #2: The numbering</strong></p>

<p>Matrix size is measured as RxC: row count, then column count, and abbreviated mxn. Items in the matrix are referenced the same way: a<sub>ij</sub> is the ith row and jth column. Mnemonics are ok <em>with context</em>, and here&#8217;s what I use:</p>

<ul>
<li>RC, like Roman Centurion or RC Cola</li>
<li>Use an &#8220;L&#8221; shape. Count down the L, then across</li>
</ul>

<p>Why does RC ordering make sense? Our operations matrix is 2&#215;3 and our input matrix is 3&#215;2. Writing them together:</p>

<pre><code>[Operation Matrix] [Input Matrix]
[operation count x operation size] [input size x input count]
[m x n] [p x q] = [m x q]
[2 x 3] [3 x 2] = [2 x 2]
</code></pre>

<p>Notice the matrices touch at the &#8220;size of operation&#8221; and &#8220;size of input&#8221; (n = p). They should match! If our inputs have 3 components, our operations should expect 3 items. In fact, we can <em>only</em> multiply matrices when n = p.</p>

<p>The output matrix has m operation rows for each input, and q inputs, giving a &#8220;m x q&#8221; matrix.</p>

<h2>Fancier Operations</h2>

<p>Let&#8217;s get comfortable with operations. Assuming 3 inputs, we can whip up a few 1-operation matrices:</p>

<ul>
<li>Adder: [1 1 1]</li>
<li>Averager: [1/3 1/3 1/3]</li>
</ul>

<p>The &#8220;Adder&#8221; is just a + b + c. The &#8220;Averager&#8221; is similar: (a + b + c)/3 = a/3 + b/3 + c/3.</p>

<p>Try these 1-liners:</p>

<ul>
<li>First-input only: [1 0 0]</li>
<li>Second-input only: [0 1 0]</li>
<li>Third-input only: [0 0 1]</li>
</ul>

<p>And if we merge them into a single matrix:</p>

<pre><code>[1 0 0]
[0 1 0]
[0 0 1]
</code></pre>

<p>Whoa &#8212; it&#8217;s the &#8220;identity matrix&#8221;, which copies 3 inputs to 3 outputs, unchanged. How about this guy?</p>

<pre><code>[1 0 0]
[0 0 1]
[0 1 0]
</code></pre>

<p>He reorders the inputs: (x, y, z) becomes (x, z, y).</p>

<p>And this one?</p>

<pre><code>[2 0 0]
[0 2 0]
[0 0 2]
</code></pre>

<p>He&#8217;s an input doubler. We could rewrite him to <code>2*I</code> (the identity matrix) if we were so inclined.</p>

<p>And yes, when we decide to treat inputs as vector coordinates, the operations matrix will transform our vectors. Here&#8217;s a <a href="http://blog.stata.com/2011/03/03/understanding-matrices-intuitively-part-1/">few examples</a>:</p>

<ul>
<li>Scale: make all inputs bigger/smaller</li>
<li>Skew: make certain inputs bigger/smaller</li>
<li>Flip: make inputs negative</li>
<li>Rotate: make new coordinates based on old ones (East becomes North, North becomes West, etc.)</li>
</ul>

<p>These are geometric interpretations of multiplication, and how to warp a vector space. Just remember that vectors are <em>examples</em> of data to modify.</p>

<h2>A Non-Vector Example: Stock Market Portfolios</h2>

<p>Let&#8217;s practice linear algebra in the real world:</p>

<ul>
<li>Input data: stock portfolios with dollars in Apple, Google and Microsoft stock</li>
<li>Operations: the changes in company values after a news event</li>
<li>Output: updated portfolios</li>
</ul>

<p>And a bonus output: let&#8217;s make a new portfolio listing the net profit/loss from the event.</p>

<p>Normally, we&#8217;d track this in a spreadsheet. Let&#8217;s learn to think with linear algebra:</p>

<ul>
<li><p>The input vector could be ($Apple, $Google, $Microsoft), showing the dollars in each stock. (Oh! These dollar values could  come from <em>another</em> matrix that multiplied the number of shares by their price. Fancy that!)</p></li>
<li><p>The 4 output operations should be: Update Apple value, Update Google value, Update Microsoft value, Compute Profit</p></li>
</ul>

<p>Visualize the problem. Imagine running through each operation:</p>

<p><img src="http://betterexplained.com/wp-content/uploads/images//linear-algebra-stock-20121002-230152.png" alt="linear algebra stock example" /></p>

<p>The key is understanding <em>why</em> we&#8217;re setting up the matrix like this, not blindly crunching numbers.</p>

<p>Got it? Let&#8217;s introduce the scenario.</p>

<p>Suppose a secret iDevice is launched: Apple jumps 20%, Google drops 5%, and Microsoft stays the same. We want to adjust each stock value, using something similar to the identity matrix:</p>

<pre><code>New Apple     [1.2  0      0]
New Google    [0    0.95   0]
New Microsoft [0    0      1]
</code></pre>

<p>The new Apple value is the original, increased by 20% (Google = 5% decrease, Microsoft = no change).</p>

<p>Oh wait! We need the overall profit:</p>

<p>Total change = (.20 * Apple) + (-.05 * Google) + (0 * Microsoft)</p>

<p>Our final operations matrix:</p>

<pre><code>New Apple       [1.2  0      0]
New Google      [0    0.95   0]
New Microsoft   [0    0      1]
Total Profit    [.20  -.05   0]
</code></pre>

<p>Making sense? Three inputs enter, four outputs leave. The first three operations are a &#8220;modified copy&#8221; and the last brings the changes together.</p>

<p>Now let&#8217;s feed in the portfolios for Alice ($1000, $1000, $1000) and Bob ($500, $2000, $500). We can crunch the numbers by hand, or use a Wolfram Alpha (<a href="http://www.wolframalpha.com/input/?i=++++%7B%7B1.2%2C0%2C0%7D%2C%7B0%2C0.95%2C0%7D%2C%7B0%2C0%2C1%7D%2C%7B.2%2C+-.05%2C+0%7D%7D+.+Transpose%28%5B%7B1000%2C+1000%2C+1000%7D%2C%7B500%2C2000%2C500%7D%5D%29">calculation</a>):</p>

<p><img src="http://betterexplained.com/wp-content/uploads/images//matrix-stock-computation-20121002-231618.png" alt="matrix stock computation" /></p>

<p>(Note: Inputs should be in columns, but it&#8217;s easier to type rows. The Transpose operation, indicated by t (tau), converts rows to columns.)</p>

<p>The final numbers: Alice has $1200 in AAPL, $950 in GOOG, $1000 in MSFT, with a net profit of $150. Bob has $600 in AAPL, $1900 in GOOG, and $500 in MSFT, with a net profit of $0.</p>

<p>What&#8217;s happening? <strong>We&#8217;re doing math with our own spreadsheet.</strong> Linear algebra emerged in the 1800s yet spreadsheets were invented in the 1980s. I blame the gap on poor linear algebra education.</p>

<h2>Historical Notes: Solving Simultaneous equations</h2>

<p>An <em>early</em> use of tables of numbers (not yet a &#8220;matrix&#8221;) was bookkeeping for linear systems:</p>

<p><img src='http://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/d9d332de6af51c511953e6fa9b7a6905.png' width='161'height='70.5' title='&#13;&#10;\begin{align*}&#13;&#10;x + 2y + 3z &amp;= 3 \\&#13;&#10;2x + 3y + 1z &amp;= -10 \\&#13;&#10;5x + -y + 2z &amp;= 14&#13;&#10;\end{align*}&#13;&#10;' alt='&#13;&#10;\begin{align*}&#13;&#10;x + 2y + 3z &amp;= 3 \\&#13;&#10;2x + 3y + 1z &amp;= -10 \\&#13;&#10;5x + -y + 2z &amp;= 14&#13;&#10;\end{align*}&#13;&#10;' align=absmiddle class='tex'></p>

<p>becomes</p>

<p><img src='http://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/791af7de3a165790db29b98b80f8eb42.png' width='211'height='66' title='&#13;&#10;\begin{bmatrix}1 &amp; 2 &amp; 3\\2 &amp; 3 &amp; 1\\5 &amp; -1 &amp; 2\end{bmatrix} \begin{bmatrix}x \\y \\ z \end{bmatrix}&#13;&#10;= \begin{bmatrix}3 \\ -10 \\ 14 \end{bmatrix}&#13;&#10;' alt='&#13;&#10;\begin{bmatrix}1 &amp; 2 &amp; 3\\2 &amp; 3 &amp; 1\\5 &amp; -1 &amp; 2\end{bmatrix} \begin{bmatrix}x \\y \\ z \end{bmatrix}&#13;&#10;= \begin{bmatrix}3 \\ -10 \\ 14 \end{bmatrix}&#13;&#10;' align=absmiddle class='tex'></p>

<p>We can avoid hand cramps by adding/subtracting rows in the matrix and output, vs. rewriting the full equations. As the matrix evolves into the identity matrix, the values of x, y and z are revealed on the output side.</p>

<p>This process, called Gauss-Jordan elimination, saves time. However, linear algebra is mainly about matrix transformations, not solving large sets of equations (it&#8217;d be like using Excel for your shopping list).</p>

<h2>Terminology, Determinants, and Eigenstuff</h2>

<p>Words have technical categories to describe their use (nouns, verbs, adjectives). Matrices can be similarly subdivided.</p>

<p>Descriptions like &#8220;upper-triangular&#8221;, &#8220;symmetric&#8221;, &#8220;diagonal&#8221; are the shape of the matrix, and influence their transformations.</p>

<p>The <strong>determinant</strong> is the &#8220;size&#8221; of the output transformation. If the input was a unit vector (representing area or volume of 1), the determinant is the size of the transformed area or volume. A determinant of 0 means matrix is &#8220;destructive&#8221; and cannot be reversed (similar to multiplying by zero: information was lost).</p>

<p>The <strong>eigenvector</strong> and <strong>eigenvalue</strong> are the &#8220;axes&#8221; of the transformation.</p>

<p>Consider a spinning globe: every location faces a new direction, except the poles.</p>

<p>An &#8220;eigenvector&#8221; is the input that doesn&#8217;t change direction after going through the matrix (it points &#8220;along the axis&#8221;). And although the direction doesn&#8217;t change, the size might. The eigenvalue is the amount the eigenvector is scaled up or down when going through the matrix.</p>

<p>(My intuition here is weak, and I&#8217;d like to explore more. Here&#8217;s a <a href="http://en.wikipedia.org/wiki/File:Eigenvectors.gif">nice diagram</a> and <a href="https://www.youtube.com/watch?v=wXCRcnbCsJA">video</a>.)</p>

<h2>Matrices As Inputs</h2>

<p>A funky thought: we can treat the operations matrix as inputs!</p>

<p>Think of a recipe as a list of commands (<em>Add 2 cups of sugar, 3 cups of flour…</em>).</p>

<p>What if we want the metric version? Take the instructions, treat them like text, and convert the units. The recipe is &#8220;input&#8221; to modify. When we&#8217;re done, we can follow the instructions again.</p>

<p>An operations matrix is similar: commands to modify. Applying one operations matrix to another gives a new operations matrix that applies <em>both</em> transformations, in order.</p>

<p>If N is &#8220;adjust for portfolio for news&#8221; and T is &#8220;adjust portfolio for taxes&#8221; then applying both:</p>

<p>TN = X</p>

<p>means &#8220;Create matrix X, which first adjusts for news, and then adjusts for taxes&#8221;. Whoa! We didn&#8217;t need an input portfolio, we applied one matrix directly to the other.</p>

<p>The beauty of linear algebra is representing an entire spreadsheet calculation with a single letter. Want to apply the same transformation a few times? Use N^2 or N^3.</p>

<h2>Can We Use Regular Addition, Please?</h2>

<p>Yes, because you asked nicely. Our &#8220;mini arithmetic&#8221; seems limiting: multiplications, but no addition? Time to expand our brains.</p>

<p>Imagine adding a dummy entry of 1 to our input: (x, y, z) becomes (x, y, z, 1).</p>

<p>Now our operations matrix has an extra, known value to play with! If we want <code>x + 1</code> we can write:</p>

<pre><code>[1 0 0 1]
</code></pre>

<p>And <code>x + y - 3</code> would be:</p>

<pre><code>[1 1 0 -3]
</code></pre>

<p>Huzzah!</p>

<p>Want the geeky explanation? We&#8217;re pretending our input exists in a 1-higher dimension, and put a &#8220;1&#8243; in that dimension. We <em>skew</em> that higher dimension, which looks like a <em>slide</em> in the current one. For example: take input (x, y, z, 1) and run it through:</p>

<pre><code>[1 0 0 1]
[0 1 0 1]
[0 0 1 1]
[0 0 0 1]
</code></pre>

<p>The result is (x + 1, y + 1, z + 1, 1). Ignoring the 4th dimension, every input got a +1. We keep the dummy entry, and can do more slides later.</p>

<p>Mini-arithmetic isn&#8217;t so limited after all.</p>

<h2>Onward</h2>

<p>I&#8217;ve overlooked some linear algebra subtleties, and I&#8217;m not too concerned. Why?</p>

<p>These metaphors are helping me <em>think</em> with matrices, more than the classes I &#8220;aced&#8221;. I can finally respond to &#8220;Why is linear algebra useful?&#8221; with &#8220;Why are spreadsheets useful?&#8221;</p>

<p>They&#8217;re not, unless you want a tool used to attack nearly every real-world problem. Ask a businessman if they&#8217;d rather donate a kidney or be banned from Excel forever. That&#8217;s the impact of linear algebra we&#8217;ve overlooked: efficient notation to bring spreadsheets into our math equations.</p>

<p>Happy math.</p>
]]></content:encoded>
			<wfw:commentRss>http://betterexplained.com/articles/linear-algebra-guide/feed/</wfw:commentRss>
		<slash:comments>34</slash:comments>
		</item>
	</channel>
</rss>
