<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
   <channel>
      <title><![CDATA[Delta Thoughts]]></title>
      <description><![CDATA[Delta Thoughts]]></description>
      <link>http://xperimex.github.io</link>
      <generator>RSS for Node</generator>
      <lastBuildDate>Mon, 06 Oct 2025 06:28:25 GMT</lastBuildDate>
      <atom:link href="http://xperimex.github.io/feed.xml" rel="self" type="application/rss+xml"/>
      <language><![CDATA[en]]></language>
      <item>
         <title><![CDATA[First Blog Post]]></title>
         <description><![CDATA[Hello, world! 

 <p><img src="/img/wildExponential.png" alt="Greetings..."></p>
<p><strong>Hello, World</strong>! I’m Adi Mittal, a student at <a href="http://terman.pausd.org">Terman Middle School</a>. I enjoy food, math, running, martial arts, and music of memes.</p>
<p>My main intent in starting this blog is to share my thoughts, ideas, and outlooks on cool math. My primary goal is to create content that&#39;s interesting and to share my thoughts on the world around me. I hope my ideas and thoughts can appeal to you, just as it did to me and showed me the interests of math!</p>
<hr>
<p><strong>UPDATE (AUGUST 1ST, 2021)</strong></p>
<p>As the years have gone by, I have moved on from my lowly middle school self and am now a rising senior at <a href="https://gunn.pausd.org/">Henry M. Gunn High School</a> who is still obsessing over math, but am also actively participating in track and field, the concert and jazz bands, Model United Nations, and acting as a key organizer in my school&#39;s <a href="https://tedxgunnhighschool.com/">TEDx organization</a>. My first year of high school was primarily situating myself in the new social dynamics and with all of these great clubs, so blogging was put on an indefinite hiatus as it floated to the back of my mind. A couple years ago, I partook in a research class in my sophomore year (which you can read about <a href="http://xperimex.com/blog/absenteeism/">here</a>) asked to summarize our work in a blog post, and it seemed like a great time to restart the site and continue writing. Since then, I&#39;ve been trying to write between school vacations, writing a couple times a month at my most efficient, but I try to get post at least once every couple of months.</p>
]]></description>
         <link>http://xperimex.github.io/blog/hello-world</link>
         <guid isPermaLink="true">http://xperimex.github.io/blog/hello-world</guid>
         <dc:creator><![CDATA[Adi Mittal]]></dc:creator>
      </item>
      <item>
         <title><![CDATA[The Math of Coins]]></title>
         <description><![CDATA[Spinning Coins 

 <p><img src="https://media.giphy.com/media/11QVoapNuz4T8A/giphy.gif" alt="Spinning Coin"></p>
<p><strong>Coins!</strong> As some of you may relate to this, I love to take a coin, and just spin it on a flat surface or table. It&#39;s just satisfying, but being put to shame by the so called &quot;Fidget Spinner&quot;. I was spinning a coin a few days ago, and was ultimately bored at the time, so I decided to ask myself a simple question: <strong>What  information from the coin can be taken away from it spinning?</strong> This then was taken into is there a <strong>correlation</strong>, or ratio, between the <strong>rate at which the coin rotates</strong>, and the <strong>rate at which it &quot;wobbles&quot;</strong>. With a goal in mind, I picked up my pencil and started to work things out.</p>
<p>First things first, defining and finding all of our givens:</p>
<p><img src="/img/coinRep2.png" alt=""></p>
<p>This diagram represents what the coin might look like at a given instance.</p>
<p>What we know about the coin:</p>
<p>The <strong>radius</strong> of our coin $= R$<br>
The <strong>circumference</strong> of our coin $C = 2 \pi R$<br></p>
<p>Now for the circle our coin rotates and wobbles upon:</p>
<p>The <strong>radius</strong> of this circle is entirely dependant on the angle of the coin to the horizontal (table/flat surface. We will define that as $\theta$). Using the diagram, we can find that $r = R \cos (\theta)$ <br>
The <strong>circumference</strong> is $c = 2 \pi R \cos (\theta)$</p>
<p>With all the givens that we need out of the way, on to the application.</p>
<p>A thing to note is that as the coin completes a <strong>full rotation</strong> around the smaller circle, the <strong>original placement of the coin moves by a certain amount</strong>. You can easily demonstrate this by drawing an arrow on a quarter, and guiding it through a rotation on a circle smaller than the quarter.</p>
<p><br></p>
<p><img src="/img/quarter2.jpg" alt=""></p>
<center>This was the quarter I used when getting ideas on how the coin behaved.</center>

<p><br></p>
<p>This extra distance it covers can easily be thought out to be as $C - c$.</p>
<center>$C - c = 2 \pi R - 2 \pi R \cos (\theta) = 2 \pi R (1 - \cos(\theta))$</center>

<p>$2 \pi R (1 - \cos(\theta)) =$ the rate at which the distance our coin completes per revolution.</p>
<p>The rate for the distance per revolution our coin completes while &quot;wobbling&quot; is the same as the circumference our coin moves around upon, which we know is $2 \pi R \cos(\theta)$</p>
<p>Putting these two together as ratio of rate of rotation, to rate of &quot;wobbling&quot;, we get:</p>
<center> $\frac{\textrm{Rate of Spinning}}{\textrm{Rate of Wobbling}} = \frac{2 \pi R \cos (1 - \theta)}{2 \pi R cos (\theta)}$<br><br> $\large= \frac{1}{\cos (\theta)} - 1$ </center>


<p>This expression represents that at any given moment, the ratio between how fast the coin is spinning, and the how fast the coin is &quot;wobbling&quot; (which can be seen as the amount of hertz produced by the coin), will be $\frac{1}{\cos (\theta)} - 1$. This also means that if you multiply the frequency of &quot;wobbling&quot; by this expression, it will output how fast the coin should be spinning at the given value of theta. For example, let&#39;s say the coin is wobbling at a frequency of $5\,hertz$ at an angle of $\frac{\pi}{4}\,radians$ (because radians are cool), the coin would have to be rotating about $4.52\,revolutions\,a\,second$ to maintain that angle to the horizontal at that &quot;wobbling&quot; frequency (because of how hertz measure $cycles\,per\,second$, the cycles translate into revolutions for the output). </p>
<p>Of course, this is all theoretical. In practice, the coin may slip. Wind may change the local air pressure, thus changing the air resistance. Everything needs to stay <strong>constant</strong>, with no disturbances or changes occuring during the coin&#39;s movement. But this is still a neat thing if you were to ask me!</p>
<p>Just to recap, we took the basics and givens of our coin and it&#39;s enviornment. Used those to get the generalized rates of the coin spinning and wobbling. We then used those calculate our ratio between the two at a given instant. Not bad!</p>
<p>If you have any questions or comments, send me an email or leave a comment!</p>
]]></description>
         <link>http://xperimex.github.io/blog/math-of-coins</link>
         <guid isPermaLink="true">http://xperimex.github.io/blog/math-of-coins</guid>
         <dc:creator><![CDATA[Adi Mittal]]></dc:creator>
      </item>
      <item>
         <title><![CDATA[Trial and Eventual-Success]]></title>
         <description><![CDATA[This triangle though... 

 <p><img src="" alt=""></p>
<p><strong>How do you... How do you even...</strong> This is when you know the problem you are about to be shown, will be annoying. When a friend of mine first introduced this problem, I thought this would be very, VERY simple, to solve. Use some angle properties, use the given similar triangles, and soon enough, a solution will be found. Of course this didn&#39;t work. I tried a few other things, same result. Showed it to my family, not much help was gained. They tried what I did. Then it hit me. The goal is to find a specific <strong>measure</strong> of the <strong>triangle</strong>s. <strong>Trigonometry</strong> $=$ The <strong>Measurement of Triangles</strong>. The solution quickly followed using a specific property, and I was like, &quot;Meh. That was quite obvious.&quot; Enough ranting, it&#39;s time you got a look at the problem itself.</p>
<p><br>
<em>In the diagram below,</em> $\angle ABC = \angle ACB = \angle DEC = \angle CDE$, $\,\overline {BC} = 8$, <em>and</em> $\,\overline {DB} = 2$. <em>Find</em> $\,\overline {AB}$
<img src="/img/trollTriangle.png" alt=""></p>
<p><br>
When drawing everyting out...</p>
<p><img src="/img/trollTriangleGiven.png" alt=""></p>
<center>
<em>SPOILER ALERT</em>
<br>
Before you continue reading, I highly encourage you attempt this geometry problem. It&#39;s an interesting problem, and once you found the concept you need to use to solve it, it&#39;s all an easy ride down from there. Following this warning will be the full solution and my thoughts on how I solved this myself. I know I already talked about my thoughts and how I solved this a little in the beginning of this post, but from here on will be <em>everything</em> I thought about.
<br>
<strong>You have been warned...</strong>
</center>
<br><br>

The property I thought of (after my 45 minutes of trial-and-error) that we can use to solve for $\,\overline {AB}$ is the <strong>The Law of Sines</strong>, which states:
<center>
$\large \frac{a}{\sin A} = \frac{b}{\sin B} = \frac{c}{\sin C}$
<br><br>
Where $A$ is the angle oposite of $a$, $\,B$ is the angle oposite of $b$, and $C$ is the angle oposite of $c$.
</center>

<p>We can rewrite this using the diagram:</p>
<center>

$\large \frac{\overline{BC}}{\sin \angle BAC} = \frac{\overline{AC}}{\sin \angle ABC} = \frac{\overline{AB}}{\sin \angle ACB}$

</center>

<p><br>
So now that we have this written out, we can start solving for $\,\overline {AB}$. For convenience, I&#39;m going to refer to the angles equivalent to $\,\angle ABC$ as $\,\theta$.</p>
<p>Using the <strong>Angle Sum Theorem</strong>, $\,\angle BAC = 180 - 2 \theta$. Using this, we can find an expression equal to $\,\overline {AB}$.</p>
<center>

$\large \frac{\overline {BC}}{\sin \angle BAC} = \frac{\overline {AB}}{\sin \angle ACB}$

<br><br>Doing some substitution...<br><br>

$\large \frac{8}{\sin 2 \theta} = \frac{\overline {AB}}{\sin \theta}$


</center>


<p>For where the $\sin 2 \theta$ came from, $\sin 180 - 2 \theta$ when evaluated, is the same as $\sin 2 \theta$. Now for some expansion and evaluation...</p>
<center>

$\large \frac{8}{2 \sin \theta \cos \theta} = \frac{\overline {AB}}{\sin \theta}$

<br><br>

$\overline {AB} \sin \theta \cos \theta = 4 \sin \theta$

<br><br>

$\overline {AB} = \large \frac{4}{\cos \theta}$

</center>

<p>Now that we have an <strong>expression</strong> for $\overline {AB}$, we just need to find a value of $\cos \theta$, and that will give us the length of $\overline {AB}$! So now, what can we do? What I first thought (based on the information we were given), if we find two expressions representing the value of the <strong>same side length</strong>, we can set those two expressions to equal one another, to find a value that makes that equation true. That equation will mostly likely output a value of a function of an angle, as we know very few side lengths, and know no angles (we&#39;re hoping it would output a value of $\cos \theta$). Again, this is only what I was thinking when solving this problem at the time. The only reason I thought this, is that I noticed two triangles, that were similar to $\triangle ABC$, contained within $\triangle ABC$. </p>
<p><img src="/img/trollTriangleSimilars.png" alt=""></p>
<p><br></p>
<p>We have similar triangles $\triangle DEC$ and $\triangle BEC$. And we know that they are similar as the both triangles share the same angles ($\theta, \theta, and \,180 - \theta$) as the original triangle $\triangle ABC$. And rememeber that side length I mentioned earlier that we could find two expressions for, and use those to solve for its length (that&#39;s a mouthful)? That length is $\overline {CE}$! It shares a side length with $\triangle DEC$ and $\triangle BEC$, and we can find our two expressions, by solving for the length of $\overline {CE}$ once, in $\triangle DEC$, and again in $\triangle BEC$. Agian, we&#39;re hoping for a value of $\cos \theta$. Starting by solving for $\triangle BEC$...</p>
<p>We are given the length of $\overline {BC} = 8$, which simplifies our job quite a bit. We can do the same thing we did to find an expression for $\overline {AB}$: Use the <strong>Law of Sines</strong>!</p>
<center>

$\large \frac{8}{\sin \theta} = \frac{\overline {CE}}{\sin 2 \theta}$

<br><br>

$\large \frac{8}{\sin \theta} = \frac{\overline {CE}}{2 \sin \theta \cos \theta}$

<br><br>

$\overline {CE} \sin \theta = 16 \sin \theta \cos \theta$

<br><br>

$\overline {CE} = 16 \cos \theta$


</center>


<p><br></p>
<p>We now have a value of $\overline {CE}$ from $\triangle BEC$, time to solve $\overline {CE}$ for $\triangle DEC$...</p>
<p><br>
First off, all though it&#39;s not stated, we know the length of $\overline {DE}$. $\triangle BEC$ is an isosceles, where $\angle BEC = \angle ECB$, which also means $\overline {BC} = \overline {BE}$. As $\overline {BC} = 8$, therfore $\overline {BE} = 8$. Since we were told $\overline {DB} = 2$, we can solve $\overline {BE} - \overline {BD} = \overline {DE} = 6$. Now back to the all-mighty, <strong>Law of Sines</strong>...</p>
<center>

$\large \frac{\overline {DE}}{\sin 2 \theta} = \frac{\overline {CE}}{\sin \theta}$

<br><br>

Substitution and expansion...

<br><br>

$\large \frac{3}{\sin \theta \cos \theta} = \frac{\overline {CE}}{\sin \theta}$

<br><br>

$\overline {CE} \sin \theta \cos \theta = 3 \sin \theta$

<br><br>

$\overline {CE} = \large \frac{3}{\cos \theta}$

</center>

<p><br></p>
<p>Great! We&#39;re lucky that it came out as a value of $\cos \theta$, but anyways, we have our two expressions, now just to set them equal to one another...</p>
<center>


$16 \cos \theta = \large \frac{3}{\cos \theta}$

<br><br>

$16 \cos^2 \theta = 3$

<br><br>


$cos^2 \theta = \large \frac{3}{16}$

<br><br>

$\cos \theta = \large \frac{\sqrt{3}}{4}$


</center>

<p><br></p>
<p>Now that we have our value of $\cos \theta$, we can just substitute this into our original expression for $\overline {AB}$...</p>
<center>

$\overline {AB} = \large \frac{4}{\cos \theta}$

<br><br>

$= \large \frac{4}{(\frac{\sqrt{3}}{4})}$

<br><br>

$ = \large \frac{16}{\sqrt{3}}$
</center>


<p><br></p>
<p>And there it would be, our solution! Although it might of seemed quite lengthy to get to $\frac{16}{\sqrt{3}}$, it all just revolved around the one concept of the <strong>Law of Sines</strong>, so not to bad.</p>
<p><br></p>
<p>Although this is one way to obtain the solution, I&#39;m sure there are other ways to tackle this problem, and I found another way which completely negates our first step, to find an expression for $\overline {AB}$, but adds an extra step to the end.</p>
<p><br>
With our value of $\cos \theta = \frac{\sqrt{3}}{4}$, we can draw a right triangle with this as one of our angles with a bit moving around.</p>
<center>

$\theta = \arccos \large \frac {\sqrt{3}}{4}$

</center>

<p><img src="/img/trollTriangleRight.png" alt=""></p>
<p><br></p>
<p>We can do this, because as we stated earlier $\theta = any\,angle\,equivalent\,to\, \angle ABC$ (and that&#39;s the exact angle we&#39;re working with). We also <strong>bisected</strong> $\overline {BC}$ at $F$ to form the 2 right triangles within our isosceles triangle, so the length of $\overline {BF} = 4$. We can then use some basic trigonometry and evaluation to solve for $\overline {AB}$.</p>
<p><br></p>
<center>

$\theta = \arccos \large \frac {\sqrt{3}}{4}$
<br><br>

$\cos \theta = \large \frac {4}{\overline {AB}}$

<br><br>

$\cos (\arccos \large \frac {\sqrt{3}}{4}) = \large \frac {4}{\overline {AB}}$

<br><br>

$\large \frac {\sqrt{3}}{4} = \large \frac {4}{\overline {AB}}$

<br><br>

${\large \frac {\sqrt{3}}{4}} \overline {AB} = 4$

<br><br>

$\overline {AB} = \large \frac{16}{\sqrt{3}}$

</center>
<br>
Just another simple way of getting to the exact same answer.


<br><br>
If you have any questions or comments, send me an email or leave a comment!




<br><br><br>

<strong>EDIT (JULY 3RD, 2017): RECURSIVE DIVISIONS SOLUTION</strong>

<br>

This specific solution, is one of my favorites that I have seen. One of my inital attempts was to use the dimensions of the similar triangels and find the common ratio between the side length and the base of the triangle. I knew it could be done, but never put my finger on it. However, when a friend of mine took a look at this problem, after a bit of thought, he managed to come up with this. It&#39;s really quite a spectacular of a solution, and this is credited entirely to him (no use of name for privacy reasons). Oh, and I&#39;ll be speaking in first person, just so I don&#39;t cause any confusion, or make it seem like I&#39;m taking it as mine. Just to be clear.

<br>

So the first step is to take the three triangles we know to be similar to one another ($\triangle ABC, \triangle BEC, and \triangle CED$. We know that they are similar due to the fact they all share two common angles, which force them to have a common ratio between the base and a leg of the triangle. This will be important to remember later), and we will $0-index$ them from the original triangle, to the following divisions within one another. I will also now be referring to the triangles by their respective index numbers.

<img src="/img/trollTriangleDivided.png" alt="">

<br>

Now using the fact that every triangle is similar, and that each progressive triangle was formed by using the base length of the previous triangle to form the leg of the next triangle, we can find a ratio between a dimension (say, the base) of a triangle, and its previous/next triangle, and use that to find the length of $\overline{AB}$. I know that is kind of confusing right now, but trust me, it will makes more sense the more I go on.

<br>

So we know the base length of two bases of two triangles ($\triangle 0$, and $\triangle 2$). Since we know that they should share a common ratio, we can right them as a ratio between one another, and hence find said ratio.

<br><center>

$\large \frac{\overline{BC}}{\overline{DE}} = \frac{8}{6}$

<br><br>

$\large = \frac{4}{3}$

<br>

</center>

<p>So we have a ratio, but the problem with this ratio it&#39;s for two divisions. It&#39;s for going between $\triangle 0$ and $\triangle 2$. We want one between $\triangle 0$ and $\triangle 1$, or $\triangle 1$ and $\triangle 2$. But this is easy! Since a division in this case is a factor of the previous triangle. This means if we take some dimenstion _a_ of a triangle, multiply it by our ratio <strong>once</strong>, we will obtain the dimension _a_ of the next division&#39;s triangle. For an example, if we have triangle-base $\overline{BC}$, and multiply it by our ratio, we should get the length of triangle-base $\overline{EC}$. Take a look at the diagram if that helps. Essentially, the base length of $\triangle 0$, multiplied by some ratio, we will get the base length of $\triangle 2$, and do that again, we will get the base length of $\triangle 3$. Now if you see, we had to multiply <strong>twice</strong> to get from $\triangle 0$ to $\triangle 2$. A.K.A., take the square of the ratio. To undo a square, you take the <strong>squareroot</strong>. So we can undo our two-division ratio, by taking the squareroot of that, to get our one-division ratio.
<br></p>
<center>

$\sqrt{\large{\frac{4}{3}}} = \large{\frac{2}{\sqrt{3}}}$ 

</center>

<p>So that&#39;s our ratio between a one triangle division. So now we need to find the length of $\overline{AB}$. So we can do what we did originally with the base lengths, only with the legs of the triangle. Larger triangle, over the divided triangle. In this case, $\triangle 0$ over $\triangle 1$.</p>
<p><br></p>
<center>

<p>$\large \frac{\overline{AB}}{\overline{BC}} = \frac{2}{\sqrt{3}}$</p>
<p><br><br></p>
<p>$\large \frac{\overline{AB}}{8} = \frac{2}{\sqrt{3}}$</p>
<p><br><br></p>
<p>$\overline{AB} = \large \frac{2 \cdot 8}{\sqrt{3}}$</p>
<p><br><br></p>
<p>$\overline{AB} = \large \frac{16}{\sqrt{3}}$</p>
<p><br>
</center>
And there it is! The answer we had before. I cannot tell you how cool of a solution this is. Simple in concept, but well executed. So major props to my friend for carrying out such a clean solution. I tried this, completely missed the obvious, and he did not. Major props to him.</p>
]]></description>
         <link>http://xperimex.github.io/blog/similar-trangles-problem</link>
         <guid isPermaLink="true">http://xperimex.github.io/blog/similar-trangles-problem</guid>
         <dc:creator><![CDATA[Adi Mittal]]></dc:creator>
      </item>
      <item>
         <title><![CDATA[How fast can I travel? Part 1]]></title>
         <description><![CDATA[Answer: Too fast 

 <p><img src="" alt=""></p>
<p>The Earth has a diameter of approximately 12742000 meters. Most people of course wouldn&#39;t travel that far, but what if you did? How fast can you get across with nothing but yourself? That&#39;s essentially what people have asked in the form of the question: How long will it take to fall through the center of the Earth?
<br><br></p>
<center>

<em>SPOLIER WARINING:</em><br>

<em>THIS WARNING IS TO INDICATE ANY WORD FOLLOWING THIS MESSAGE WILL BE A PART OF THE SOLUTION TO THIS PROBLEM. HIGHLY ENCOURAGE THE ATTEMPT TO SOLVE THIS PROBLEM.</em> <br>

<em>YOU HAVE BEEN WARNED...</em>


</center>
<br><br><br> Following our standard procedure, let&#39;s list all the givens:

<br>
<center>
$The\,radius\,of\,the\,Earth is R = 6,371,000$ meters

<br><br>
$The\,Force\,of\,Gravity\,is\,F = \large \frac{G m M}{r^2}$
<br><br>
Where...<br> $G = Gravity$<br>
$m = Mass\,of\,Object_1\, (in\,this\,case,\,us)$<br>
$M = Mass\,of\,Object_2\,(in\,this\,case,\,Earth)$<br>
$r = the\,distance\,between\,m\,and\,M.$
</center>

<p>So now we are just trying to find as many values or expressions to variables within that eqauation of force. We can leave $m$ as is, becuase that&#39;s the mass of our human/us. So what we really need is $r$ and $M$.</p>
<p><img src="/img/earthModel.png" alt=""></p>
<p><br></p>
<p>One thing we have to worry about though, is that as we fall $r$ will change. As we fall we will get clsoer to Earth&#39;s center of mass, eventually pass it, and then get farther from it. So we will call our current distance relative to Earth&#39;s center of mass as $x$. And what&#39;s great about this, if we are any distance into our fall, we can just ignore any mass above us. Using the diagram as an example, if we are $R-x$ deep into our fall, we can ignore any mass of Earth contained between $R$ and $x$. Some of you may think, &quot;But wait! Wouldn&#39;t the mass above us have it&#39;s own force of gravity acting upon you, and therefore slowing you down as you fall?&quot; The answer is technically yes, but that all balances out with the mass <em>below</em> you and to the <em>side of</em> you. All these forces cancel out, making it not affect you at all. So, all we really care about is the amount of mass below us, and the distance between us and the Earth&#39;s center of mass (which would be the radius $x$ as we have been discussing). So we have one variable filled.</p>
<p><br></p>
<center>

$F = \large \frac{G m M}{x^2}$

</center>

<p>Now we need $M$. The formula for mass is $M = volume \times density$. The volume of the Earth $= \frac{4 \pi x^3}{3}$ (we are using $x$ again as the mass affecting us changes over our fall). And we can represent density with $\rho$. So the $M$ equals:</p>
<p><br></p>
<center>

$\large \frac{4 \pi \rho x^3}{3}$

</center>

<p>Putting this all together, the force of gravity acting upon us during this fall equals:</p>
<p><br></p>
<center>

$F = \large \frac{4 \pi G m \rho x^3}{3 x^2}$
<br><br>

$ = \large \frac{4 \pi G m \rho}{3} x$

</center>

<p>If we let $\frac{4 \pi G m \rho}{3} =$ say, v, we get $F = -v x$. It&#39;s negative because we are falling first. This is actually an <strong>oscillating system</strong>. To represent this, I&#39;ve made a mock graph to show how gravity affects us over time starting from the top of &quot;Earth&quot;. The graph is just a representation.</p>
<p><img src="/img/oscillatingModel.png" alt=""></p>
<p><br></p>
<p>If the x-axis is time, and we fell from the top of Earth (and there is NO air resistence), as you can see, we would just continuously bounce back and forth between the top and bottom of the Earth. Now we need to find the <strong>period</strong> of our oscillating system. The period is the time it takes for one cycle to be completed. To be more precise, we need <em>half</em> of the period. That is because one cycle (in this case) is falling all the way down, and coming all the way back. We only want the time it takes to fall down, so that&#39;s why the half.</p>
<p>The eqauation for the period of a simple oscillating system (also called a harmonic motion) is:</p>
<p><br></p>
<center>

$P = 2 \pi \sqrt {\large \frac {m}{k}}$


</center>


<p>The variable representation is that $k$ is our oscillating system, and $m$ is our mass. But since we want half of that, so therefor time to fall through the Earth is...</p>
<p><br></p>
<center>

$Time = \pi \sqrt {\large \frac {m}{k}}$
<br><br>
Doing some substitution...

<br><br>


$Time = \pi \sqrt {\large \frac {m}{\large \frac{4 \pi G m \rho}{3}}}$

<br><br>

$ = \pi \sqrt {\large \frac {3 m }{4 \pi G m \rho}}$

<br><br>

$ = \sqrt {\large \frac {3 m \pi^2}{4 \pi G m \rho}}$

<br><br>

$ = \sqrt {\large \frac {3 \pi}{4 G \rho}}$


</center>

<p>Now all we need to do is put in $G$ as the Gravitational Constant, and $\rho$ as the density ($\rho = \frac{mass}{volume}$) of Earth (I did some Googling...)!</p>
<p><br></p>
<center>

$Time = \sqrt {\large \frac {3 \pi}{4 \cdot 6.67408 \cdot 10^{-11} \cdot m^3 \cdot kg^{-1} \cdot s^{-2} \cdot \frac{5.972 \cdot 10^{24}\, kg}{\frac{4 \pi \cdot 6371000^3}{3} \, m^3} }}$

<br><br>

</center> This looks bad. Let&#39;s clean it up.
<br><br>

<center>
$= \sqrt {\large \frac {3 \pi}{4 \cdot 6.67408 \cdot 10^{-11} \cdot m^3 \cdot kg^{-1} \cdot s^{-2} \cdot \frac{5.972 \cdot 10^{24} \cdot 3 \, kg}{4 \pi \cdot 6371000^3 \, m^3} }}$

<br><br>

$= \sqrt {\large \frac {3 \pi}{4 \cdot 6.67408 \cdot 10^{-11} \cdot s^{-2} \cdot \frac{5.972 \cdot 10^{24} \cdot 3}{4 \pi \cdot 6371000^3} }}$

<br><br>

$ = \sqrt {\large \frac {3 \pi \cdot s^{2}}{4 \cdot 6.67408 \cdot 10^{-11} \cdot \frac{5.972 \cdot 10^{24} \cdot 3}{4 \pi \cdot 6371000^3} }}$

<br><br>


$ = s \sqrt {\large \frac {3 \pi}{4 \cdot 6.67408 \cdot 10^{-11} \cdot \frac{5.972 \cdot 10^{24} \cdot 3}{4 \pi \cdot 6371000^3} }}$

</center>

<p>So, I don&#39;t know about you, but when I have something like this, I just straight up put it into <a href ="http://www.m.wolframalpha.com"> <em>Wolfram Alpha</em> </a>, or a similar calculator, as I am just lazy and it&#39;s a pain to evaluate. So, letting it be computed by the calculator...</p>
<p><br></p>
<center>

$Time = s \sqrt {\large \frac {3 \pi}{4 \cdot 6.67408 \cdot 10^{-11} \cdot \frac{5.972 \cdot 10^{24} \cdot 3}{4 \pi \cdot 6371000^3} }}$

<br><br>

$ \large = 2530.5\,seconds$

</center>

<p>This, funnily enough is also the answer to the universe and all of its questions. $2530.5\,seconds = 42\,minutes\,(+10.5\,seconds)$. Quite a coincidence if I say so!</p>
<p><br></p>
<p>Now what&#39;s great about our equation we used ($ = \sqrt {\frac {3 \pi}{4 G \rho}}$), it&#39;s quite easy to apply to other objects, as most of it is constant! 3, is well, a constant. So is 4. $\pi$ has been universally agreed upon for its value. And as far as we can tell in the universe, the Gravitational Constant is true. The only thing that determines the fall length is the density. So you could have two planets, one with $x$ as its radius, and the other as $100 x$. If the are just as dense as one another, you will fall through them (across the diameter) in the same time.</p>
<p><br></p>
<p>Now just as a random fact that I thought was amusing, was the top speed you would attain. We know that acceleration due to gravity on Earth is $\frac{9.807\,m}{s^2}$. The top speed would be when you reach the center of the Earth, which is 6,371,000 meters from the surface (aka, the radius of Earth). Using this, we can calculate the speed at which we would be at in meters per second at the center. Just to be sure, we can calculate acceleration due to gravity, using our original formula, where we ignore our mass: $g = \frac{G \cdot M_{Earth}}{R^2}$</p>
<p><br></p>
<center>

$g = \large \frac{G \cdot M_{Earth} }{R^2}$


<br><br>

</center> Substituting everything we have... <center> <br><br>

$g = \frac{6.67408 \cdot 10^{-11} \cdot m^3 \cdot kg^{-1} \cdot s^{-2} \cdot 5.972 \cdot 10^{24}\, kg }{6371000^2\,m^2}$

<br><br>

$g = \frac{6.67408 \cdot 5.972 \cdot 10^{13} \cdot m}{6371000^2 \cdot s^2}$

<br><br>

Thanks to a calculator...

<br><br>

$\approx \large\frac{9.82m}{s^2}$

</center>

<p>Of course this is not the same as what others have put on the internet, values will differ from here to there. I trust the value of $\frac{9.807m}{s^2}, as I think there values they used to calculate it would be more accurate. Back to the top speed now.</p>
<p><br></p>
<center>

$g = \large \frac{9.807\,m}{s^2}$

<br><br>

$ = \large \frac{9.807 \cdot 6371000}{s^2}$

<br><br>

$ = \large \frac{\sqrt{9.807 \cdot 6371000}}{s}$

<br><br>

$\approx \large \frac{7904.454251 m}{s}$

<br>
</center>
Which is equivalent to...

<br><br>

<center>

$\approx \large \frac{28456.035304\,km}{hour}$

<br><br>

$\approx \large \frac{17681.760583\,miles}{hour}$

</center>

<p>That&#39;s about 23.23 times the speed of sound! This literally means you can&#39;t yell during this fall, as you would be going literally faster than the time it takes to vibrate the air around you. It will be a silent fall. That is, if there was air, and the terminal velcoity of a human wasn&#39;t $\frac{53m}{s}$.</p>
<p><br></p>
<p>So that would be it for this post! We found out we can cross Earth in under 45 minutes, and break the sound barrier 23 times over! <br></p>
<p>I plan on following it up with another post showing how you can use integration to find the time to fall through Earth (and that equation to find the period of an oscillating system/simple harmonic motion that kind of came out of nowhere. The $2 \pi \sqrt{\frac{m}{k}}$), and to show some other cool properties and interesting things about falling, pendulums, and oscillating systems in general.</p>
<p><br></p>
<p>Now here&#39;s an extra challenge for you: How long will it take to fall through Earth, 500 kilometers above the surface?</p>
<p><br></p>
<p>If you have any questions or comments, send me an email or leave a comment!</p>
]]></description>
         <link>http://xperimex.github.io/blog/falling-through-earth</link>
         <guid isPermaLink="true">http://xperimex.github.io/blog/falling-through-earth</guid>
         <dc:creator><![CDATA[Adi Mittal]]></dc:creator>
      </item>
      <item>
         <title><![CDATA[To equal NP or to not equal NP. That is the question.]]></title>
         <description><![CDATA[I tried... 

 <p><img src="" alt=""></p>
<p>There is just no introduction needed here. The problem at hand is probably one of the hardest, most controversial topic in computer science:
<br><br></p>
<center><em>Prove that</em> $P = NP$, <em>or otherwise</em></center>

<p><br></p>
<p>In case this is not clear (or never have heard this problem before), it is to show that all NP-hard problems are P problems, or show that they are not equal. An NP-hard problem is a problem that cannot be solved in polynomial time ($NP$ represents for non-deterministic polynomial-time, and $P$ just represents for polynomial-time). Polynomial time is time that can be represented as a function of the input (input being whatever you need to achieve/solve for in the problem), and the function is a simple polynomial function. For example, the following function representing the time it takes to solve some problem,
<br></p>
<center>$f(x) = p(x^k)$, where $k$ is constant</center>
<br>
..., this would classify the problem as a $P$ problem, as we can represent the time it takes to solve the problem as a simple polynomial function. An example for how long some $NP-hard$ problem might take to solve would be such as...
<br>
<center>$f(x) = p(k^x)$, where $k$ is constant</center>
<br>
This is bad for computation time, since $x$ is our input, our values would explode the greater the amount of input we have. That&#39;s why this is an $NP-hard$ problem. We would essentially have to brute force our, and check every possible scenario (within allotted values for our problem) to solve for this. 
<br>
So now the reason why this problem is so controversial, it&#39;s because that if we can show that $P = NP$ is true, we can then theoretically solve ANY problem within an algorithmic, and in polynomial time. It will cut so much time off of the time it takes to solve all the crazy hard, unsolved problems.

<br>
And I know, some of you may be thinking, &quot;But, hey! Wouldn&#39;t most problems need a completely different approach to solve, than another problem?&quot; Well, my response to this, would be yes, but, there are some $NP-hard$ problems that <em>have</em> been solved. These are called $NP-complete$ problems. The reason why these are important (especially when answering the above question) is because a common way to tackle these $NP-hard$ problems is by boiling it down to a smaller, similar, $NP-complete$ problem, and then brute force it in a way similar to that $NP-complete$ problem. <a href = "https://en.wikipedia.org/wiki/List_of_NP-complete_problems"> Here is a list of $NP-complete$ problems. </a>

<br><br>

<img src="/img/np-reduction.png" alt="">
<center>This here shows how you can work from one $NP-hard$ problem to another, smaller, but related problem.</center>

<p><br></p>
<p>Okay, now with that all out of the way, the reason why I started discussing $NP-problems$, the $P$ versus $NP$ problem. This problem bothers me so much, for a few reasons. <strong>ONE</strong>: This seems a lot easier to solve than it actually is, and this just intuitively bothers me more than other problems do. It seems like such a simple statement to show, but it&#39;s just not. <strong>TWO</strong>: The way people are approaching this problem, it seems all to <em>awkward</em> and incorrect to me. It seems that they are overcomplicating this quite a bit. But this is computer science, so I don&#39;t have much say. And the person who proved <em>Fermat&#39;s Last Theorem</em> did so in more or less 150 pages (I think), so this could very well be so as well.</p>
<p><br></p>
<p>My attempts haven&#39;t been as successful (well, if it was successful, I would be too excited to write this up), but I do have a few thoughts on the matter. My first attempt was rather bleak. Take a generalized form of the time it takes to solve an $NP-hard$ problem, and just try to work it down to some representation of polynomial time. This obviously, did not work. What ended up happening was that I was trying to represent the wrong variable into polynomial-time representation, and couldn&#39;t find a way to expand on onto the variable that I needed to express. So, that idea was gone. The second idea, would be a bit more practical. Take some $NP-complete$ problem, look at it how it&#39;s time is in its NP form, then try to find some algorithm that results in the same solution, but is in polynomial time. The reason why I would do this, is because you can link almost any $NP-problem$ to one of the $NP-complete$ problems. Using this, we can creat a map, linking every $NP-complete$ problem to another. That way, if we can solve for one, we have then technically shown for every $NP-problem$. We can do that, or generalize somehow our $NP-complete$ problem, and show from there. My last idea on the matter, is to think of the consequences of this statement ($P=NP$) of being <strong>true</strong>, or <strong>false</strong>. If this is <strong>true</strong>, I feel that this would create a paradox. Because finding the polynomial-time fuction of a $NP-problem$ is $NP-hard$ in itself. But that cannot happen, as we said that $P=NP$, so we have a contradiction in itself. So you would then have to show that finding a P function of a NP function is in P. But that is also $NP-hard$. Then you would have to show that is also in P. But that&#39;s also $NP-hard$, so we have to show that it&#39;s in P, etc., etc. So we end up with having to contiuously prove that something that is in NP is in P, to show that the smaller $NP-hard$ problem of P versus NP (showing the conversion of NP to P in a given $NP-problem$), is also in P (that was a bit long and a mouthful. Essentially you get a recursive $NP-problem$, and each iteration of this recursive problem is slightly different than the last iteration, but with the same goal of showing that that iteration of an $NP-problem$ takes P time to actually solve). If it was <strong>false</strong>, we would stay where we are computationally, and nothing would of changed. Personally, based on what I have done so far, I think $P \neq NP$. But don&#39;t think that is my final decision. People have shown $NP-hard$ problems to be computed in polynomial-time, so based on my second idea of mapping $NP-complete$ problems, there is still some possibility. Expect some updates, and future posts, as this is one of many other problems (I&#39;ll just say them: The Millenium Problems) that have gotten me thinking in almost no way I have done before (that&#39;s probably because they are not all math-based, and I&#39;m a math-based guy, so math-based + not-math-based-problem = new type of thinking). Actually, don&#39;t expect future updates and posts, just know there will be future updates and posts.</p>
<p><br><br>
If you have any questions or comments, send me an email or leave a comment!</p>
]]></description>
         <link>http://xperimex.github.io/blog/p-vs-np</link>
         <guid isPermaLink="true">http://xperimex.github.io/blog/p-vs-np</guid>
         <dc:creator><![CDATA[Adi Mittal]]></dc:creator>
      </item>
      <item>
         <title><![CDATA[(Un)Expected Value]]></title>
         <description><![CDATA[Okay, you don't make that much... 

 <p><img src="" alt=""></p>
<p>Not much for an introduction this post. Found this problem when looking for interesting problems for myself. Shoutout to <a href = "https://www.physics.harvard.edu/academics/undergrad/problems">Harvard&#39;s Problem of the Week</a> (from 2002 to 2004). The problem at hand is:</p>
<center>

Consider the following game: You flip a coin until you get tails, and the amount of money you win is equal to number of coins you end up flipping (i.e. If you flip a coin, and immediately get tails, you win one dollar. If it takes 2 flips to get tails, you get 2 dollars. 3 flips = 3 dollars. So on, and so on).
<br><br>
(a) What is your expected value you win when playing the game?
<br><br>
(b) Play the same game, except let your earnings be $2^{n-1}$, where $n$ is the amount of flips. What do you expect to win now? Does it make sense?

</center>

<p><br><br><br></p>
<center><strong>SPOILER WARNING: SOLUTION INCOMING</strong></center>

<p><br><br><br></p>
<p><strong>(a)</strong>: Expected value is the amount you win, multiplied by the probability of it occuring, and adding up all the possible outcomes.
<br>
You have a 50% chance to win 1 dollar. 25% chance to win 2 dollars. 12.5% chance to win 3 dollars...</p>
<p><br></p>
<center>

<p>$\large \frac{1}{2} + \frac{2}{4} + \frac{3}{8} + \frac{4}{16} + ...$</p>
<p><br><br></p>
<p>$= \large \sum _{n=1}^{\infty }\: \frac{n}{2^n}$
<br><br></p>
<p>$= \large 2$</p>
<p><br><br></p>
<p><strong>OR</strong></p>
<p><br><br>
$\large \frac{1}{2} + \frac{2}{4} + \frac{3}{8} + \frac{4}{16} + ...$</p>
<p><br><br>
$\large =(\frac{1}{2} + \frac{1}{4} + \frac{1}{8} + \frac{1}{6} + ...) + (\frac{1}{4} + \frac{1}{8} + \frac{1}{16} + ...) + (\frac{1}{8} + \frac{1}{16} + ...) + ...$</p>
<p><br><br></p>
<p>$= (1) + \large (\frac{1}{2}) + (\frac{1}{4}) + (\frac{1}{8}) + (\frac{1}{16}) +...$</p>
<p><br><br></p>
<p>$\large = 2$
</center>
<br>
So you can expect to win <strong>2 dollars</strong> every time you play this game.</p>
<p><br>
This is where the fun is at.</p>
<p><br>
<strong>(b)</strong>: We have 50% chance to win 1 dollar. We have a 25% chance to win 2 dollars. We have a 12.5% chance to win 4 dollars...
<br></p>
<center>

<p>$\large \frac{1}{2} + \frac{2}{4} + \frac{4}{8} + \frac{8}{16} +...$</p>
<p><br><br>
If you don&#39;t mind, since I like to write things in sigma notation, I would like to write the simplified verison of this sum in sigma notation.
<br><br></p>
<p>$=\large \sum _{n=1}^{\infty}\: \frac{1}{2}$
<br><br></p>
<p>$\large = \infty$</p>
<p></center>
<br>
This is why I picked this problem. The first part is quite simple, but this part creates quite a dilemma. What can we do now? How should we interpret this for the expected value of our game? Now one would ever put up a game in which the player is expected to win an infinte amount of money, since no one has an infinite amount money!
<br></p>
<p>The following explanation is a jumble between what I thought, and Harvard&#39;s. I recommend looking at what they <a href = "https://www.physics.harvard.edu/uploads/files/undergrad/probweek/sol6.pdf">said</a> specifically.</p>
<p><br></p>
<p>The solution is that our game (would be known as the <em>experiment</em> in our scenario) doesn&#39;t agree with the exact definition of <strong>expected value</strong>. Expected value is defined as an average over an <em>infinite</em> amount of attempts/trials (this can be viewed at least as the limit towards an infinite number of attempts/trials). The thing is that, you&#39;ll never be able to play an infinite amount of games. Essentially, our experiment (game) doesn&#39;t agree with our calculated expected value, as the experiment has nothing to do whatsoever with the precise defintion of expected value. Just as an example, if you were to (somehow) play an infinite amount of games, your earnings would indeed average an infinite amount. This whole idea of this expecting to win an infinite amount, and it &quot;not working/making sense/not being possible&quot; arises when we try to make expected value, something it isn&#39;t.</p>
<p><br> Okay, I like math, but from this point onward I didn&#39;t have much. And what I did wasn&#39;t cohesive, as 25% was written down, the other 75% was in my head. The problem is, that 75% <em>was</em> in my head. I would try to go through and get my complete explanation, but I feel that Harvard&#39;s solution is already quite nice. So the rest is all Harvard&#39;s explanation. Only credit I get here is for the fact I formatted it for this page. Here you go.<br></p>
<p>&quot;<em>This might not be a very satisfying explanation, so let us get a better feeling for the problem by looking at a situation where someone plays $N = 2^n$ games. How much money would a “reasonable” person be willing to put up front for the opportunity to play these N games? Well, in about $2^{n−1}$ games he will win one dollar; in about 2^{n−2} he will win two dollars; in about $2^{n−3}$ games he will win four dollars; etc., until in about one game he will win $2^{n−1}$ dollars. In addition, there are the “fractional” numbers of games where he wins much larger quantities of money (for example, inhalf a game he will win $2^n$ dollars, etc.), and this is indeed where the infinite expectation value comes from, in the calculation above. But let us forget about these for the moment, in order to just get a lower bound on what a reasonable person should put on the table. Adding up the above cases gives the total winnings as: $2^{n−1}(1) + 2^{n−2}(2) + 2^{n−3}(4) +· · ·+ 1(2^{n−1}) = 2^{n−1}n$. The average value of these winnings in the $N = 2^n$ games is therefore $\frac{2^{n−1}n}{2^n} = \frac{n}{2} = \frac{(\log_2 N)}{2}$. A reasonable person should therefore expect to win at least $\frac{(\log_2 N)}{2}$ dollars per game. (By “expect”, we mean that if the player plays a very large number of sets of $N$ games, and then takes an average over these sets, he will win at least $2^{n−1}n$ dollars per set.) This clearly increases with $N$, and goes to infinity as $N$ goes to infinity. It is nice to see that we can obtain this infinite limit without having to worry about what happens in the infinite number of “fractional” games. Remember, though, that this quantity, $\frac{(\log_2 N)}{2}$, has nothing to do with a true expectation value, which is only defined for $N → ∞$. Someone may still not be satisfied and want to ask, “But what if I play only $N$ games? I will never ever play another game. How much money do I expect to win?” The proper answer is that the question has no meaning. It is not possible to define how much one expects to win, if one is not willing to take an average over a arbitrarily large number of trials.</em>&quot;</p>
<p><br><br></p>
<p>Neat little problem if I do say so myself. Some of my work, some of Harvard&#39;s, hope it was cohesive and clear who was writing what when. I wish I could of gotten my last piece of explanation, just would of taken a bit too long for something I need to redo. Moral of the story: Take complete notes.</p>
<p><br><br>
If you have any questions or comments, send me an email or leave a comment!</p>
]]></description>
         <link>http://xperimex.github.io/blog/flipping-coins</link>
         <guid isPermaLink="true">http://xperimex.github.io/blog/flipping-coins</guid>
         <dc:creator><![CDATA[Adi Mittal]]></dc:creator>
      </item>
      <item>
         <title><![CDATA[Persuasion is Hard]]></title>
         <description><![CDATA[System 1 and System 2 Persuasion Tactics and Their Impacts on Secondary School Absenteeism 

 <p>This was done as part of the Advanced Authentic Research program during the 2019-2020 academic school year.</p>
<hr>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <strong>Over 7 million students</strong> across the United States missed 15+ days of school in the 2015-16 school year (US Department of Education, 2012). These <em>chronically absent</em> who miss 10% of their academic year cause over 40 <em>billion</em> worth of instructional minutes to go to waste. Even more jarring, in the same report, it was cited that inconsistent student attendance is a better indicator than test scores to whether a student will drop out of school or not. In case it wasn&#39;t clear enough, student absenteeism is a major issue haunting the education system, and the need find a solution to it is greater than ever. Over the past 8 months, I have conducted a small series of experiments to try and alter the state of this issue in one public high school in Palo Alto, California.</p>
<h2 id="introduction">Introduction</h2>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <strong>In the case of Palo Alto&#39;s Henry M. Gunn High School</strong>, only 5% of the school&#39;s 2000 students are in this category of the chronically absent. That means on average, 1 student is missing in every class on campus. What makes this statistic concerning though is when one considers the demographic of Palo Alto. Here are two maps of the United States: one of the median household income (New York Public Radio), and another of chronic absentee rates by district (US Department of Education, 2012).</p>
<center>

<table>
<colgroup>
       <col span="1" style="width: 44.25105485%;">
       <col span="2" style="width: 55.74894515%;">
</colgroup>
<tr>
<td>
<a href="/img/medianIncome1.png">
<img src="/img/medianIncome1.png" height=300 />
</a>
</td>
<td>
<a href="/img/absenteeRate.png">
<img src="/img/absenteeRate.png" height=300 />
</a>
</td>
</tr>
</table>

</center>

<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Although Palo Alto is in one of the most affluent neighborhoods in the nation, its chronic absentee rate is equal to some areas with with not even half its median household income. This led to the idea that absenteeism may be fueled by different motivators across the country. For example, in some less fortunate neighborhoods, kids may be an active contributor to their family income, leading to conflicts with their academic commitment. Similarly, because of Palo Alto&#39;s wealth and greater access to resources, academic competitiveness may fuel absenteeism. This may seem counterintuitive at first: if someone wants to do well in class, why would they skip it? These <em>strategic absentees</em> skip class not because they want to, but rather as a necessary evil: they feel the need to skip a class a means to prepare for another one. These are the students that can most affect the absentee rate, as not only are they motivated to go to class, but their absences are likely more sporadic than they standard chronically absent, meaning that they are more likely to be in class to be influenced by a teacher or administrator, which nicely leads into the next section.</p>
<h2 id="nudges">Nudges</h2>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <strong>Students can&#39;t be forced to go to class</strong>. Especially as Henry M. Gunn High School sports an open-campus policy, it is impossible to be able to force a substantial number of absentees to go to class beyond the already instated measures. So, instead, we tried to <strong>persuade</strong> the students, as if they agree for themselves attending class is the right thing to do, they are more likely to act on it. To do so, we used specially engineered social measures to try and convince the students as best as possible, known as <strong>nudges</strong>.</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Nudges, at their core, are suggestions. They don&#39;t affect one&#39;s ability to choose, but they utilize the person&#39;s experience to guide them to pick an option. The most commonly used nudge utilizes comparisons: let&#39;s say a restaurant has a dish that doesn&#39;t sell super well, and is ultimately costing them money having it listed on the menu. To boost its sales, they can list a slightly cheaper dish that has no intention of actually being sold in large quantities. This &quot;fake&quot; dish provides a reference frame for the buyer, making what originally seemed as overprice as suddenly as a great deal. The first time this type of persuasion was first formalized in a book of the same name: <em>Nudge: Improving Decisions About Health, Wealth, and Happiness</em>, written by Cass Sunstein and Richard Thaler (<a href="https://www.amazon.com/Nudge-Improving-Decisions-Health-Happiness/dp/014311526X"> highly recommended read </a>). It should be reiterated that this doesn&#39;t change one&#39;s ability to pick what food item they want, and that&#39;s what makes a nudge so effective. It allows the person to convince themselves without needing to feel as if the choice was imposed on them (i.e. remove everything on the menu except one dish). This is a form of <em>indirect persuasion</em>: we&#39;re not explicitly saying what we want the affected person to do, but we are adding information to guide one choice over another. The counterpart to this would be <em>direct persuasion</em>: giving explicit desires for which option to choose.</p>
<h2 id="experimental-model">Experimental Model</h2>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <strong>This project employed 2 types of persuasion tactics that were each disseminated via 2 types of mediums</strong>. The two types of mediums you are already familiar with: direct and indirect persuasion. This was examined by having the teacher give information by describing a set of data (see below) for direct persuasion. Indirect persuasion was tested by having the environment give the information, meaning instead of having the teacher give information on data, the students take in the information for themselves by noticing the data as a poster in the classroom. Now, I have been purposely vague about what data was shown to the students as there were actually <em>two</em> different sets of data that were shown to different classes, but they communicated the same idea.</p>
<p><a href="/img/dataStimuli1.png">
<img src="/img/dataStimuli1.png" height=250 />
</a></p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; If these curves look the same, that&#39;s because they are; they are the same set of data, but one is presented with a positive connotation (attendance is good) and the other with a negative connotation (absenteeism is bad). These are the two sets of data presented, as to see whether <em>how</em> one presents data affects one&#39;s ability to influence.</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; So, in total, there are 5 classes: $\mathrm{i})$ teacher presents positive connotation data; $\mathrm{ii})$ teacher presents negative connotation data; $\mathrm{iii})$ classroom presents positive connotation data; $\mathrm{iv})$ classroom presents negative connotation data; and lastly, all compared to a  $\mathrm{v})$ control with no intervention (this is formally known as <a href="https://en.wikipedia.org/wiki/Framing_effect_(psychology">framing</a>)).</p>
<h2 id="results">Results</h2>
<p><a href="/img/results.png">
<img src="/img/results.png" height=450 />
</a></p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; As you can see, there are 5 lines shown on the graph: 4 lines, 2 blue and 2 red, to represent data collected and a green line that represents the aforementioned Gunn&#39;s 5% chronic absentee rate. The blue lines represent tardy and absentee data from January, to collect pre-experimental data. Red lines represent data collected in February, the month in which the experiment was set in motion.</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; This graph may be a bit intimidating to read, but it helps to realize that the x-axis is not a representation of time like most line graphs, but rather are the individual class models. This allows for easy comparison between months, as if there was, say, a virus moving throughout the classes that caused a 3% increase to absences to all classes, it will look as if one line was shifted upwards, having the same structure more or less to the other.</p>
<h2 id="analyses">Analyses</h2>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; These results are really surprising, as there was <em>no</em> improvement at all from any implementation of our stimulus. If anything, it got marginally <em>worse</em> with a slight increase to tardies in all classes ($\approx$3-4% increase). Which makes some sense as when you consider whenever someone commands you to do something or says you&#39;re doing something wrong, the first instinct is to disagree and defend your actions. This feeling is known as <strong>reactance</strong>, and it is likely what caused this mild increase in tardies.</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; What is extremely concerning however is the massive increase in absences seen in the &quot;-/teacher&quot; class (negative connotation data presented by teacher), which observed an astonishing <strong>85% increase</strong> in absences. That is the difference between another <strong>90 additional students</strong> absent in Gunn, and an <strong>additional 560 across all of the Palo Alto Unified School District</strong>. This incites an interesting thought: <strong>subconscious effects, such as reactance, can be amplified by other effects as well</strong>. In this case, it was the <em>negativity bias</em> -- the idea that negative connotations tend to be overestimated in their impact than positive ones -- that amplified the reactance. For instance, say you are an avid fan of the fruit, apples. If someone says oranges are better than apples, reactance will be incurred and you&#39;ll likely disagree. If someone says apples are worse than oranges, however, now there is this feeling of losing an opinion as well, amplifying the disagreement. Here, it is the difference between saying attending class is better than skipping it, and vice versa.</p>
<h2 id="conclusion">Conclusion</h2>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <strong>These results are highly specific</strong>. Before you try to go and apply these ideas beyond the realm of this project, you should consider who were subject to this experiment. In fact, I had witnessed this exact concept during my trials: the inspiration for an easy experimental model was inspired by Moore (2004), who conducted an almost identical scenario of my experiment and found it to be effective for <em>university</em> students, while mine showed to not be effective for high schoolers. Further testing is needed, but the greatest takeaway from this experiment is that communication and persuasion is something that can only be achieved when it is very specifically tailored for a specific audience.</p>
<p><br></p>
<hr>
<p>If you want to read to a higher degree of depth on the matter, everything cited here and more can be found in my <a href="/img/absenteePaper.pdf">original paper</a>.</p>
<hr>
<p><br></p>
<h2 id="process">Process</h2>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <strong>Originally, this project was never supposed to be about attendance</strong>. Originally, I was intending on studying voting theory as I was (and still am) super interested in how individual behavior affects the collective, and how that can be leveraged. I was looking at networks and graph theory, synchronization, and other related topics, but I was especially looking at behavioral economics and prospect theory. Realizing I was about a year too early to be able to study any recent elections or voting processes, I honed in on the behavioral economics aspect of the research, and started to look for a new problem to address. I talked to Gunn High School&#39;s principal on school issues that could be examined, and attendance was a recurring theme. This was only corroborated by the <em>California Healthy Kids Survey</em>, a questionnaire that surveyed 9th and 11th graders each year, and it reported that 7% of freshmen and 11% of juniors cut class to prepare for another class alone in the month the survey was distributed (California Department of Education, 2017-18). So, I started directing my attention to different studies and papers that were already conducted to learn what ideas have been tried and tested, such as what Moore (2004) and Self (2012) did.</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Very quickly on, however, I realized I was probably going to have the same issue that I was going to have with voting theory: gathering original experimental data. Not that there is anything wrong with using pre-existing data, I personally wanted to collect my own original data to analyze, especially as I wasn&#39;t sure if something like attendance would be internalized the same way in a high school population as the more frequently studied college population (and as stated previously, there was in fact a discrepancy between Moore&#39;s and my findings due to different populations studied). So, I began reaching out to different teachers to see who would be willing to help run the experiment in their classes. Doing so proved to be very difficult, as I needed a teacher who taught at least 5 classes of 20+ students that had some absentees in each class, who also had the class time to be able to explain the necessary information to 2 classes. I was able to properly contact 2 teachers, one of which I was able to collect data for, and the other I was not due to the sudden COVID-19 outbreak.</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Another thing that made this project difficult was that I had an incredible workload set out for this year. Between the 5 required academic classes, 2 electives, an after-school elective, club commitments, and a sport for two-thirds of the year, I just didn&#39;t have the time in my schedule to devote another 2+ hours of class time, which didn&#39;t even include time needed outside of class to research and write. Not to mention any extracurriculars I had in place as well. I had to schedule almost all of my meetings at 7am or earlier, or worse, do them entirely across email threads, which made communication ambiguous and difficult at times.</p>
<p>Regardless, this whole experience taught me so much about academia beyond the scope of what any high school classroom could have, and taught me how no matter no simple a question one has, willing to ask it can lead to incredible results.</p>
<h2 id="about-aar">About AAR</h2>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; As stated at the top, this was done as part of the <a href="https://aar.pausd.org/"> <b>A</b>dvanced <b>A</b>uthentic <b>R</b>esearch</a> program that PAUSD provides to its two high schools as a means to introduce students to formal research and academic writing, well beyond what a standard English class essay or chemistry lab write-up teaches. Providing students with community mentors, experts, and connections, it fosters student growth via the students&#39; own motivation to learn, creating an environment where projects, such as the former, can be created out of curiosity, and not by seeking a letter on a report card.</p>
]]></description>
         <link>http://xperimex.github.io/blog/absenteeism</link>
         <guid isPermaLink="true">http://xperimex.github.io/blog/absenteeism</guid>
         <dc:creator><![CDATA[Adi Mittal]]></dc:creator>
      </item>
      <item>
         <title><![CDATA[Golden Quartics]]></title>
         <description><![CDATA[The hidden relationship of quartics and phi 

 <meta name="viewport" content="width=device-width">

<script src="https://www.desmos.com/api/v1.5/calculator.js?apiKey=dcb31709b452b1cf9dc26972add0fda6"></script>

<p>This post looks to describe an interesting property intrinsic to any and all quartic functions, and it has to do with the relationship between the functions&#39; inflection points. Below is a Desmos graph, with labeled $f(x)=Ax^4+Bx^3+Cx^2+Dx+E$, the general quartic equation, as well as its 2 inflection points $P$ and $Q$. A third point $R$ is labeled, which is the point that intersects the line between $P$ and $Q$ and $f(x)$. What we are interested in today is the ratio $\frac{PR}{PQ}$. Play with the graph below to vary $f(x)$ and see what happens to that ratio.</p>
<center>
  <div id="intro" style="width: 660px; height: 570px;"></div>

  <script src="/js/introGraph.js"></script>
</center>

<p>Quickly you will notice that for (most) non-zero $A$ values, $\frac{PR}{PQ}$ always remains at the rather famous constant, $\varphi=1.61803...$, the golden ratio. This may seem coincidental, but there is a rather nice way of proving that this ratio is <em>exactly</em> equal to the golden ratio.</p>
<h2 id="the-golden-ratio">The Golden Ratio</h2>
<p>The classic definition of $\varphi$ comes from a specific geometric construction of a rectangle.</p>
<center>
<img src="/img/goldenRectangle.png" style="background-color: #fff;">
</center>

<p>In this <em>golden rectangle</em>, there are two rectangles to focus on: the large one with aspect ratio $\frac{a+b}{a}$, and the smaller red one with aspect ratio $\frac{a}{b}$. The golden ratio is given by $\frac{a}{b}$ when the small red rectangle has the <em>same</em> aspect ratio as the larger rectangle (made up of the blue square and red rectangle). Letting $\varphi=\frac{a}{b}$, and setting the ratios equal to each other nets us:</p>
<center>
<!-- $\frac{a+b}{a}=\frac{a}{b}$
<br>
$1+\frac{b}{a}=\frac{a}{b}$
<br>
$1+\frac{1}{\varphi}=\varphi$
<br>
$\varphi+1=\varphi^2$
<br>
$\varphi^2-\varphi-1=0$
<br>
$\varphi=\large{ \frac{1 \pm \sqrt{5}}{2} }$ -->

$\begin{align}
  \frac{a+b}{a} &amp; = \frac{a}{b} \
  \newline
  1+\frac{b}{a} &amp; = \frac{a}{b} \
  \newline
  1+\frac{1}{\varphi} &amp; = \varphi \
  \newline
  \varphi+1 &amp; = \varphi^2 \
  \newline
  \varphi^2-\varphi-1 &amp; = 0 \
  \newline
\end{align}$
<br><br>
$\large{\varphi = \large{\frac{1 \pm \sqrt{5}}{2}}}$

</center>

<p>The positive solution to this quadratic is the more well known value $\varphi$. Taking some variations of the previous equations can net other interesting relationships that $\varphi$ pertains to. For example, taking the third line from the derivation of $\varphi$ nets a recursive, cyclic definition of the golden ratio. Expanding out the relation gives another famous definition of $\varphi$.</p>
<center>
$\varphi = 1 + \large{ \frac{1}{1 + \frac{1}{1 + \frac{1}{1 + \frac{1}{\ddots}}}} }$
</center>

<p>An infinite descending fraction solely containing 1s. Taking a variation of the fourth line also gives an interesting appearance of $\varphi$.</p>
<center>
$\varphi = \sqrt{1 + \sqrt{1 + \sqrt{1 + \sqrt{1 + \ldots}}}}$
</center>

<p>An infinitely nested radical solely containing 1s. Notice, however, that the solution to the golden ratio has a negative counter part as well: $1-\varphi=-.61803$. Although it may seem nonsensical to assign a negative value to many of the expressions we used in defining $\varphi$, this value holds many of the same properties that $\varphi$ holds on its own as well, and the reason we don&#39;t see it as often has to do with the volatility of the value in these iterated scenarios, but that&#39;s for <a href="http://xperimex.com/blog/fixed-points/">another time</a>.</p>
<h2 id="the-proof">The Proof</h2>
<p>First, let&#39;s look at how to find the inflection points of a quartic. Inflection points are given by the quality that it&#39;s the point along a function where its concavity changes. I.e. if you look at the tangent lines along a curve as you vary the input $x$, the tangent lines&#39; slopes will change. The inflection points are found when the slopes&#39; behavior alters. Take the function $x^3$, for example.</p>
<center>
  <div id="exampleInflection" style="width: 660px; height: 300px;"></div>
  <script src="/js/exampleInflection.js"></script>
</center>


<p>Notice how as we let our value $a$ increase, the slope of our tangent line — the first derivative of $f(x)$ — decreases from $-1.5$ to $0$. But from $0$ to $1.5$, the slope begins to increase. This is all visualized in our graph $f&#39;(x)$ which plots every point $x$ and the value of its slope at $f(x)$. One can clearly see $f&#39;(x)$ tends in a downward manner initially, before rising again. And for $f&#39;(x)$ to have a slope that&#39;s first negative (decreasing) then positive (increasing), it must have a slope of zero in between. So, our point where our concavity changes is when the slope of $f&#39;(x)$ equals 0. In other words, when the second derivative $f&#39;&#39;(x)=0$. Here we can see it clearly visualized at the solution $x=0$, which confirms all of our previous observations. Doing so for any general quartic nets us:</p>
<center>
$\begin{align}
f(x) &amp; = Ax^4+Bx^3+Cx^2+Dx+E \
\newline
f&#39;(x) &amp; = 4Ax^3+3Bx^2+2Cx+D \
\newline
f&#39;&#39;(x) &amp; = 12Ax^2+6Bx+2C = 0
\end{align}$
</center>

<p>As this is a degree 2 polynomial, the quadratic formula quickly gives our two solutions for $x$ in general, which we will call $p$ and $q$.</p>
<center>
$p = \large{ \frac{-3B-\sqrt{9B^2-24AC}}{12A} }$ &nbsp;&nbsp; $q = \large{ \frac{-3B+\sqrt{9B^2-24AC}}{12A} }$
</center>

<p>This also explains why only most values of our constants have inflection points, as if the $9B^2-24AC$ term is negative, it results in an imaginary solution, meaning no inflection point is found within the real plane. With valid constants giving us solutions for our inflection points $P$ and $Q$ respectively, the line through them can quickly be written as:</p>
<center>
$g(x)=\frac{f(q)-f(p)}{q-p}(x-p)+f(p)$
</center>

<p>The intersection point $R$ can be found solving for when $f(x)=g(x)$, or in other words, when $f(x)-g(x)=0$</p>
<center>
$f(x)-g(x)=0$
<br>
$Ax^4+Bx^3+Cx^2+Dx+E-\frac{f(q)-f(p)}{q-p}(x-p)-f(p) = 0$
</center>

<p>One can try to factor and work this out, but there is a much nicer approach that avoids working with this messy equation.</p>
<h2 id="transformations">Transformations</h2>
<p>If we limit our transformations to purely scaling and translating our graph, all of our ratios will remain equivalent. So if we can find a set of transformations to make our work easier, we will still be able to prove our initial proposition, but in a much easier way. To (re)start, we&#39;re going to define a new function $h(x)$ that takes $f(x)$, and scales and moves it around as follows:</p>
<center>
$h(x) = \frac{1}{q-p}(f([q-p]x+p)-f(p))$
</center>

<p>This may seem arbitrary, but keeping in mind what $p$ and $q$ mean, this transformation alters the graph in a rather specific and useful way. First notice these two key components in our transformation:</p>
<center>
$h(x) = \frac{1}{q-p}(f([q-p]x+{\bf p})-{\bf f(p)})$
</center>

<p>This results in shifting the graph over to the left $p$ units and down $f(p)$ units. Or more clearly, it takes our first inflection point $(p,f(p)) \rightarrow (0,0)$, the origin. We&#39;ll refer to the origin as $P&#39;$. Now, let&#39;s look at the remaining components of the transformation:</p>
<center>
$h(x) = {\bf \frac{1}{q-p} }(f({\bf [q-p]}x+p)-f(p))$
</center>

<p>Multiplying $x$ by $q-p$ results in <em>compressing</em> the $x$-axis by a factor of $q-p$. So, the x coordinate distance between our inflection points is condensed from a length of $q-p$ to a length $\frac{q-p}{q-p} = 1$. Just to keep our scaling consistent throughout $f(x)$, we also scale the $y$-axis down by a factor $q-p$, so we add an extra factor of $\frac{1}{q-p}$. This factor is almost purely for aesthetic purposes, as you will see it will preserve the structure of our graphs and make it easier to see our scaled copy of $f(x)$ in $h(x)$. So, as the difference in $x$ coordinates between $P&#39;$ and $Q&#39;$ is 1, $Q&#39;$ will be at $(1,h(1))$. $R&#39;$ will retain its same definition as $R$, differing only in that it is on our newly transformed function.</p>
<center>
  <div id="transformedGraph" style="width: 660px; height: 530px;"></div>
  <script src="/js/transformedGraph.js"></script>
</center>

<p>Notice how the two inflection lines are parallel. That is due to that extra factor of $\frac{1}{q-p}$ in $h(x)$, but note that the math that follows is not dependent on it.</p>
<p>It&#39;s worth noting that we don&#39;t actually know any of the constants that shape our new quartic $h(x)=ax^4+bx^3+cx^2+dx+e$ as they don&#39;t change according to our scaling factors (notice the change in capitalization; these new constants for $h(x)$ is separate and different to those of $f(x)$). However, we do know the solutions to $h&#39;&#39;(x)=0$. Instead of using our function to find its second derivative like we did in our original approach, we are working backwards from our second derivative to narrow in on our function. Since we know where our inflection points are at, we can rewrite our $h&#39;&#39;(x)$ as a product of factors.</p>
<center>
$h&#39;&#39;(x)=0 \rightarrow x=P&#39;,Q&#39; \rightarrow x=0,1 \rightarrow h&#39;&#39;(x)=12ax(x-1)$
</center>

<p>The factor of $12a$ comes from the leading term when taking the second derivative of any general quartic, as we saw in the original attempt to prove this. Expanding this expression and integrating twice gives us:</p>
<center>
$\begin{align}
  h&#39;&#39;(x) &amp; = 12ax(x-1)=12ax^2-12ax \
  \newline
  h&#39;(x) &amp; = 4ax^3-6ax^2+b \
  \newline
  h(x) &amp; = ax^4-2ax^3+bx
\end{align}$
</center>

<p>Notice I didn&#39;t add a new constant after the second integration, as that is equivalent to the $y$-intercept, which we know to be at $(0,0)$. Now that we have $h(x)$ in terms of itself, separated from $f(x)$, we can easily find the coordinates of $Q&#39;$ and find $h(1)$.</p>
<center>
$h(1)=a(1)^4-2a(1)^3+b(1)=b-a \rightarrow Q&#39;:(1,b-a)$
</center>

<p>Now we can create a new secant line $g(x)$ to pass through our two inflection points, $P&#39;:(0,0)$ and $Q&#39;:(1,b-a)$.</p>
<center>
$g(x)=\frac{b-a-0}{1-0}(x-0)+0=(b-a)x$
</center>

<p>Now we can continue using our original method, which is to find all solutions to $h(x)-g(x)=0$. Only this time, our transformations should net a cleaner equation.</p>
<center>
$\begin{align}
  h(x)-g(x) &amp; = 0 \
  \newline
  ax^4-2ax^3+bx-(b-a)x &amp; = 0 \
  \newline
  ax^4-2ax^3+bx-bx+ax &amp; = 0 \
  \newline
  ax^4-2ax^3+ax &amp; = 0 \
  \newline
  ax(x^3-2x^2+1) &amp; = 0 
  \end{align}$
</center>

<p>That $ax$ we factored out is our solution at $x=0$, or $P&#39;$, which we used to construct the line in the first place. Similarly, because we used $Q&#39;$ to construct the line as well at $x=1$, we can factor out an $x-1$ as well.</p>
<center>
$\begin{align}
  ax(x^3-2x^2+1) &amp; = 0 \
  \newline
  ax(x-1)(x^2-x-1) &amp; = 0
\end{align}$
</center>

<p>That last factor is the exact quadratic that we derived to define the golden ratio. Knowing that, we now have all of our solutions to the intersection points between our quartic and secant line.</p>
<center>
$x=0,1,\large{ \frac{1 \pm \sqrt{5}}{2} }$
</center>

<p>The negative solution to the golden ratio here is the fourth point of intersection at $S:(s,h(s))$ with $s&lt;0$. Now the last thing to note is that our 3 points of interest, $P&#39;$, $Q&#39;$, and $R&#39;$, are all collinear. So, they can be thought of as a projection of the $x$-axis to a sloped line that scales how far they are spaced apart. However, since this is multiplicative, the ratios will be the same, so we only need to look at the ratios between their $x$ coordinates.</p>
<center>
$\large{ \frac{PR}{PQ} = \large{ \frac{P&#39;R&#39;}{P&#39;Q&#39;} } = \frac{\frac{1 + \sqrt{5}}{2} - 0}{1 - 0} = \varphi }$
</center>

<p>You can also quickly find other ratios of different lengths and find other interesting connections. Take $\frac{PQ}{QR}$, for example.</p>
<center>
$\large{ \frac{PQ}{QR} = \large{ \frac{P&#39;Q&#39;}{Q&#39;R&#39;} } = \frac{1 - 0}{\frac{1 + \sqrt{5}}{2} - 1} = \frac{1}{\varphi-1} }$
</center>

<p>If you look at our defining quadratic $\varphi^2-\varphi-1=0$, it can be rewritten as $\varphi(\varphi-1)=1 \rightarrow \varphi=\frac{1}{\varphi-1}$. Completing our expression gives us:</p>
<center>
$\large{ \frac{PQ}{QR} = \large{ \frac{P&#39;Q&#39;}{Q&#39;R&#39;} } = \frac{1 - 0}{\frac{1 + \sqrt{5}}{2} - 1} = \frac{1}{\varphi-1} = \varphi}$
</center>

<p>Just as our golden rectangle previously foretold.</p>
]]></description>
         <link>http://xperimex.github.io/blog/golden-quartics</link>
         <guid isPermaLink="true">http://xperimex.github.io/blog/golden-quartics</guid>
         <dc:creator><![CDATA[Adi Mittal]]></dc:creator>
      </item>
      <item>
         <title><![CDATA[Retroreflectors]]></title>
         <description><![CDATA[The utility of right angles 

 <p>If you ever seen a bike at night, you&#39;ve likely noticed the bright reflector many people use to ensure they&#39;re visible while riding. Why are they so effective at creating such visibility? It lies in the construction of the reflector itself. Looking closely at a bicycle reflector, you will notice that they aren&#39;t just plain mirrored facets; they have an almost pixelated, grid like look to them.</p>
<p><img src="/img/retroreflector.jpg" style="width:500px; height=auto "></p>
<p>They are surfaces not covered in flat mirrors, but rather are tessellated with the corners of cubes that are mirrored. Why is that? To find out, we first need to talk about Fermat&#39;s principle, and $90^\circ$ angles.</p>
<h2 id="fermat-s-principle">Fermat&#39;s Principle</h2>
<p>Fermat&#39;s principle, or the principle of least time, was an idea coined in 1662 by the mathematician of the same name, and it states that the path taken by any given ray of light is always the quickest one. Although this may seem obvious, it allows for many properties of light and optics to be derived from it. The one that it helps demonstrate for us is the common equality of the <em>Law of Reflection</em>: the angle a light approaches a surface is the same angle it reflects at.</p>
<center>
<iframe src="https://www.desmos.com/calculator/1s5r5iqlyc?embed" width="570px" height="570px" style="border: 1px solid #ccc" frameborder=0></iframe>
</center>

<p>Let&#39;s say we have a light source $S$, and we&#39;re reflecting it off a mirror (black) at point $R$, to have our ray reach an end point $E$. To show that the angle of incidence must equal the angle of reflection, we are going to create a mirrored copy of our end point, $E&#39;$ (points $P$ and $Q$ are exclusively reference points). As $E&#39;$ is a reflection of $E$ across the mirror, they are both equidistant to $R$, so we end up with two orange lines of equal length, $\overline{RE}$ and $\overline{RE&#39;}$. However, because $\overline{RE} = \overline{RE&#39;}$, our original path of reflection $SRE$ can be modeled with the new path $SRE&#39;$. Note that the speed of the light isn&#39;t changing throughout our model, so we only need to find the shortest path $SE&#39;$. To minimize $\overline{SE&#39;}$, the shortest path is clearly just a straight line (blue). We already new that the angle $\angle{ERQ} = \angle{E&#39;RQ}$ by definition of reflection of $E \rightarrow E&#39;$, and now that we know $\overline{SE&#39;}$ is a straight line, the angle that $\angle{SRP} = \angle{E&#39;RQ}$. Combining these two inequalities nets us $\angle{SRP} = \angle{E&#39;RQ} = \angle{ERQ}$, which was what we wanted to show.</p>
<p>Although this seems like an obvious fact, knowing why it this fact is true helps to understand how we will apply it to our bike reflector and corner cubes.</p>
<h2 id="right-angles">Right Angles</h2>
<p>To understand why corner cubes are chosen as bike reflectors structure, looking at simpler cases always helps. Instead of looking at corners of cubes to see how light interacts with them, we can first work from the corner of a square and see what happens.</p>
<center>
<iframe src="https://www.desmos.com/calculator/y6c0ifjbxx?embed" width="650px" height="650px" style="border: 1px solid #ccc" frameborder=0></iframe>
</center>

<p>Notice how regardless of what angle the light is hitting the corner, the light reflected from the corner is always parallel to the ray entering it. We can prove this remains true for any angle $\alpha$ quite simply using some basic geometry.</p>
<p><img src="/img/cornerSquare1.png"></p>
<p>We want to show that ray $\overrightarrow{M}$ is parallel to $\overrightarrow{N}$ given $\overrightarrow{M}$ intersects the corner at an angle $\alpha$ and that we have a true square corner that is a right angle. Filling in the givens, the rest follows nicely. The Law of Reflection gives the angle congruent to the initial $\alpha$, and the idea that all triangles&#39; angles sum to $180^\circ$ gives the $90-\alpha$. The trick in proving this involves adding an auxiliary line as such and the rest follows.</p>
<p><img src="/img/cornerSquare2.png"></p>
<p>We add another line parallel to one of the sides of our corner. This creates another right angle. Since we know that $90-\alpha$ makes part of the right angle, we know that $\alpha$ must make up the rest of the right angle, as $90-\alpha+\alpha=90$. By Law of Reflection we then know that there is a symmetrical angle of measure $\alpha$. Now since $\overrightarrow{M}$ and $\overrightarrow{N}$ both are attached to parallel lines at congruent angles, the only way that can happen is if $\overrightarrow{M}$ was parallel to $\overrightarrow{N}$ as well. Hence, a ray $\overrightarrow{M}$ has a reflected path $\overrightarrow{N}$ that exits parallel to its ray of incidence.</p>
<p>Moreover, we can show this only holds true for right angles using very similar logic. Setting our once right angle to $\theta$...</p>
<p><img src="/img/cornerSquareGeneral.png"></p>
<p>From our diagram, it&#39;s clear that for $\overrightarrow{M}$ to be parallel to $\overrightarrow{N}$, $\alpha=\alpha+\theta-90$, which when solving for $\theta$ gives $\theta=90$, our previous right angle.</p>
<p>All of the previous arguments can be applied to the 3-dimensional case by decomposing the ray of light into two other rays, and by showing that those two rays are parallel to the initial, that the composite ray is as well. With all of this together, it makes perfect sense why bike reflectors are corners of cubes: they send light back to its source. If you had a standard mirror, no light would return back to where it came from unless looking perfectly perpendicular to the mirror.</p>
<center>
<iframe src="https://www.desmos.com/calculator/yzy5cfaimu?embed" width="650px" height="650px" style="border: 1px solid #ccc" frameborder=0></iframe>
</center>

<p>If no light goes back to its source, to say, a car&#39;s headlights, no light will hit the driver&#39;s eye to indicate that there is a bright, shining reflector to show that there is a bike up ahead (for this reason exactly, most reflectors actually have angles slightly large than 90$^\circ$ so that most light returns back to its source, and some can scatter to an observer slightly above/below/left/right of the source). These reflectors actually have a specific name to it, and they&#39;re known as <em>retroreflectors</em>, literally meaning to reflect backwards. This concept has been leveraged to aid satellites, and indirectly the military. There&#39;s a reason why no stealth-based aerial technology has no right angles: they want to avoid creating an accidental retroreflector that can return radio waves.</p>
<p>Hopefully this gave insight into a seemingly arbitrary design choice in one of the most common bike accessories used today.</p>
]]></description>
         <link>http://xperimex.github.io/blog/retroreflectors</link>
         <guid isPermaLink="true">http://xperimex.github.io/blog/retroreflectors</guid>
         <dc:creator><![CDATA[Adi Mittal]]></dc:creator>
      </item>
      <item>
         <title><![CDATA[Mad Max: Fury Road]]></title>
         <description><![CDATA[Yes, the flamethrowing guitar was necessary 

 <p>This post is a collection of essays analyzing scenes, themes, dialogue, and scoring of George Miller&#39;s 2015 120-minute action packed car chase of a movie, <em>Mad Max: Fury Road</em>. It is truly one of my favorite, raw action movies I&#39;ve seen in a long time as it knows exactly what it is: an action movie. It delivers in spades what every action enthusiasts craves with some of the wildest practical effects seen to date, it still manages to have tender moments and characters develop through the action rather than just through some corny moments or having explosions for the sake of explosions. If you have not seen it, do what you can to do so, as even if you&#39;re not a fan of action movies, <em>Fury Road</em> transcends the category and delivers so much more.</p>
<p>You should also watch it as these essays assume: a) that you know the movie so you don&#39;t walk into thousands of words of spoilers, and b) that you are familiar with some of the terminology introduced in the film as well. </p>
<p>To start, let&#39;s look at the end.</p>
<h3 id="the-end-">The End…?</h3>
<p>The ending could be a sort of allusion to the western genre as a whole (after all it is commonly referred to as a “western on wheels”). After having found his name and fulfilling his moral duties to the extent as he feels needed, Max leaves to be his lone ranger just as he started to move onto his next wandering adventure. This sort of functions with how Max blends into the crowd, illustrating how he is just as anyone in that crowd: seeking a purpose, and having now fulfilled that, he walks in the opposite direction from whichever everyone else walks, no longer looking at the Citadel nor Furiosa <em>for</em> hope, but walking away as he has already been <em>given</em> hope by it. This is furthered by the final quote presented by The First History Man at the film’s conclusion: “Where must we go, we who wander this wasteland, in search of our better selves?” This implies that the place to seek to better oneself doesn’t exist, or is unknown at the very least, and it has to do with because one of the central themes of the movie is that redemption is a self-realizing process, not one induced by a place or material object, but rather <em>conducted through</em> places, objects, and or people. They can be mediums, but not the incitation of being redeemed. Nux, having abandoned his technological faith in Immortan Joe, is a key example of the process, as he takes the phrase, “Witness me!,” to be one not of sacrificing himself, but rather as remembrance by asking the wives who he’s befriended to not forget him for the person he was rather than his death for them. </p>
<p>Returning back to Max’s extraneous leaving of the Citadel, having found redemption and reacquainting himself with his past, Max feels no obligation to stay as while the Citadel, the Wives, Furiosa, and Nux were his mediums of redemption, they weren’t a part of what he was redeeming: his quest was purely for himself and his past, ideas and memories unassociated with the movie’s setting, it’s the parallels that he inevitably sees in the other characters that draws him to help. Contrasted to the other characters’, such as aforementioned Nux, while they do have their own redemption arcs, they tie in directly to the immediate setting which gives them motive beyond personal reason to stay; they’re not only redeeming themselves, but the land itself (note that these should be treated as separate actions; intertwined as they are, Nux, Furiosa, and the Wives, redeeming the Citadel is more of a byproduct of their personal growth that was conducted through their reclaiming of the stronghold). While Max and the rest of the cast are all given hope from the present and their actions through the movie, what differentiates them is how they leverage this hope to recontextualize their life: Max feels he has atoned and repented for his guilted past, while the rest have their futures recontextualized, now knowing that they no longer lead a life of forced repression. Their repression wasn’t what likely induced their guilt, but knowing that they had little hope to have a better life at all is likely what made them feel powerless, and guilty they hadn’t attempted to advocate for a more moral society. But, because they never had that opportunity physically and only the thought, there isn’t anything in their previous life that they would be to perceive differently or acknowledge: they did what they could, and they only have the future to look forward to, and we see this time and time again in the intermittent sequences which the cast breaks from the intensity of the chase scenes: Furiosa is seeking to return to her dearly beloved home, the Green Place; the Wives are motivated, almost haunted by the prospect of a haven away from Immortan Joe’s abuse (I phrase the Green Place like this as they have no concrete image of it, and are seeking the concept not necessarily a specific place); Nux is seeking technological salvation, and to make his half-life existence meaningful (similarly, Valhalla is phrased like this, as he’s motivated by the concept, not the place as he’s only ever had it described to him, he’s never seen it); these are all motives that they envision in the future for themselves, not something they are gripping on to from the past. It just so happens that in the narrative, all of these instances of their individual sanctum sanctorum converge on the Citadel over the course of their character growth as they realize that they can only seek comfort in reforming their personas, so while the direct action they take switches from materialistic to impersonal, the motivation remains the same for a prospect of the future. This is why everyone but Max staying is so crucial, as it maintains the consistency of the messaging and the individual character plots we’ve been presented with throughout the course of the movie. This film’s ending is merely a means to help individualize Max’s personal journey from the thematic and character development that underpins the work’s message and structure.</p>
<p>My last thought on the end is that this could potentially hint at how this film wasn’t necessarily completely true, but rather a myth or legend passed on. The idea of there being a <em>first</em> history man implies there are others, too, all who pass on and carry stories such as what is told in <em>Fury Road</em>, similar to how in <em>Mad Max 2: The Road Warrior</em>, the narrator of the film wasn’t Max at all, but rather a survivor who was helped by him. So perhaps, the ending quote not only explains why Max left, but potentially how everyone interpreted why he left after all they have endured: Max is a legend looking for his next outpost to wander into, to better another untouched aspect of his life we’ve yet to be revealed. Just as old cliché westerns reiterate time and time again of the wandering, lone hero who’s been mythologized and solidified in glorious memory, perhaps <em>Fury Road</em>, intended for Max to represent just that: a memory to inspire. However, this would still help maintain all of the previous messaging aforementioned, as whether he was diegetically existent as the movie presents or just a fable, his story of proposing redemption still maintains the inspirational quality that he is remembered for anyway. It’s only the scope of the amount of people it reaches that changes.</p>
<h3 id="feminism-and-the-vuvalini">Feminism and the Vuvalini</h3>
<p>There is definitely a feminist connotation and tone in throughout the film, but feminism is not the complete term based on its etymology. To be concrete from the start, according to Merriam-Webster, the term “feminism” is used to describe “the theory of political, economic, and social equality of the sexes; organizing activity on behalf of women’s rights and interests.” Even though the first definition is gender neutral, based on the word’s etymology and the more popularly associated second definition, this response will be referring to that definition of feminism throughout this response, and it’s the gender specific terminology is what prevents classifying this film as a feminist one. While it’s perfectly reasonable to say that this film exhibits feminist messaging, it’s more justified to argue that this is a more specific case tailored to our own social context in reality that is being related to the film, rather than the broader, more powerful message at hand. Given our, the audience’s, perspective on our very own society’s development and history with gender inequality, the lead antagonist being male with extremely powerful women protagonist counterparts, these are prime conditions to further a feminist message. The issue is, however, these exact messages function almost equivalently with the genders swapped in the film: if Immortan Joe was a female counterpart, the Wives and other protagonists were primarily male, the film could still be classified as feminist, which may seem contradictory, until acknowledging the innate messaging surrounding not just women, but humanity as a whole. Take the standard woman in Immortan Joe’s world: they’re treated essentially to the extent of a rape victim, being sexually abused solely for their fertility; their reduced to an object of a single purpose to forcibly bring life to Immortan’s subjects and the Citadel (this association of fertility and women is supported by the Vuvalini’s own Keeper of the Seeds who seeks to plant and sprout a new life of the Green Place). So, to have a contrast in extremely powerful women between the nomadic Vuvalini, the Wives, and Furiosa, who end up conquering Immortan Joe in the end coupled with the one of the final shots of the women releasing the “aqua-cola” to the people makes for a very strong feminist message, which in that sense, it is understandable that some critics characterizing this film as feminist. However, it’s hard to ignore the parallels between the male characters’ portrayals throughout the film. Max, even before the title card of the film has played, Max is similarly bound and exploited for his social benefits, which instead of being fertility, is holding a healthy supply of O- universally donatable blood for Immortan’s War Boys, who themselves are exploited in their own ways. War Boys, instead of being exploited for their ability to give life, it’s their ability to take it, and execute Immortan’s visions of destruction. However, more importantly than the roles themselves, is their relation to the characters themselves as these roles even reverse with Furiosa and Max by the end, where Max becomes inducted into the Vuvalini and even heals Furiosa under his own volition to perform a blood transfusion on her, while Furiosa is the one to ultimately kill Immortan Joe at the end. These intermixing of the movie’s established gender roles further blur the lines to say which gender is being empowered more, by essentially neglecting the need for it to exist and categorize the characters at all; what defined women and their exploitation, and hence motive to revolt in an empowered fashion gets reassociated with the opposite gender, making it hard to define it as a distinct trait, and hence more apt to look at it as role-specific retaliations and revolts when it is a part of a greater collective body of both genders. Similar parallels can be found between major sacrifices in the movie: Nux from the, War Boys, sacrifices himself specifically to give the women (implied more than to end Immortan’s soldiers’ lives by his care for Capable) a chance to lead a longer, more fulfilling life, while many of the Vuvalini give their life to end Immortan’s army as they stand diametrically opposed to their own morals of community (see the scene where Max convinces the group to redirect themselves towards attacking the Citadel). There’s a constant defying of expectations to mirror and reverse supposed gender-specific roles within the film to unify the genders as one. So while there is in fact a large component that empowers women, due to the parallels that the men’s stories provide, it’s more accurate to say that this is a movie about empowering humanity as a whole above the tyranny and unethical practices that Immortan Joe embodies (it’s not surprising that Immortan Joe’s name mimics not only the word “immoral” in addition to “immortal”). Even the name of the stronghold the protagonists reclaim, the Citadel, echoes deeply not just the despot they’re overthrowing, but the entire symbol for oppression: it’s not just a fortress dominating people, it is an empire dominating the humanity of the people.</p>
<p>One fact that might augment the message to be a bit more women-centric, though, is the naming of the Wives: Angharad (Welsh name for “much loved one”), The Dag (Australian slang for “funny/amusing”), Toast the Knowing, Cheedo the Fragile, and Capable, each seemingly named after a core value they embody of charismatic/leader-like, comedic, wise, fragile, and confident respectively. With each embodying an extremely distinct human quality, it’s hard not to see how they themselves personify humanity as a group. That combined with their distinct light, (relatively) elegant clothing, the group also clearly is hope incarnate, which can seen most distinctly during the nighttime Green Place car chase scene with the Bullet Farmer, where they are the ones seen to be holding the only lightsource between the crew of the War Rig, contrasting the deep, unsettling emptiness of the exhausted, corrupted Green Place. However, when interpreted like this, it’s worth noting how the <em>other</em> characters perceive the Wives: they are the ultimate prize. Immortan Joe seeks them to bear healthy children, so in a literal sense, the Wives are the ultimate material possession for him. However, Max, Furiosa, Nux, and other aiding protagonists are not drawn to the Wives for their physical traits, but rather because of who they represent; they want to protect the Wives as they are the characteristics of humanity they all seek to restore themselves, which furthers the lack of gender as a needed category of a theme. When perceived as symbols, the Wives exemplify a much greater presence in the film as the “MacGuffin” that everyone seeks to find and protect as a medium to try and redeem some humanity within themselves; the core values they represent ends up being a universally sought after, set of appreciable qualities.</p>
<h3 id="furiosa-s-story">Furiosa&#39;s Story</h3>
<p>Furiosa was born into the Green Place as the daughter of Mary Jabassa of the tribe Swaddle Dog of the Vuvalini, being taught and trained by her “initiate mother” K.T. Concannon. There, in her matriarchal society, she is taught to value her relationships and who she is in this tribe of mothers. However, she was abducted – stolen – from her home by Immortan Joe to the Citadel along with her mother, who died within 3 days of captivity. Immortan Joe took in Furiosa as one of his new wives, seeking for her to bear his new healthy son. Unable to successfully impregnate her with a possible heir, Immortan Joe had no use for her to serve in his vault as a breeder. Unable to watch a possible “resource” go underutilized, Immortan Joe gave Furiosa to one of his Imperators, a high commanding military officer who takes control of their invaluable War Rigs. Constantly exposed to war and automotive technology, Furiosa became an experienced, and newly indispensable asset from one unable to give life to others, to one able to quickly and efficiently take it. But, only so much experience can provide so much benefit without repercussions: she lost an arm in combat, forcing her to create a prosthetic extension to be able to continue serving. Once her half-life mentor had passed, she replaced his title and claimed Imperator for herself as a leader in Immortan Joe’s ranks, becoming one of his most trusted commanding officers and couriers. Due to his trust and surplus of willing warriors, Immortan Joe assigned Furiosa to watch over his most prized possessions that Furiosa was once almost inducted into: his prized breeders, the Five Wives. Relating to their physical abuse, the Wives were the first people since Furiosa’s capture that she connects with. The abuse and effort she had to commit to, though, took a toll on Furiosa across her 7000 days of imprisonment. On many occasions, she has considered defecting and escaping in search of her once lost Green Place and taking refuge in her family. Holding as much power as she did with her War Rig, she saw an opportunity, a clear one no less, to retrace her path, running from Immortan’s grasp, and find her lost home among the barren deserts of a once fruitful land. She tries to leave, but not alone: Furiosa smuggles the Five Wives with her, knowing they need the Green Place just as much as she does.</p>
<p>The first bit of basic information is given directly through her identity speech upon regrouping with the Vuvalini for the first time. We learn about her compassion and love of her people through her introductory speech to the Vuvalini: she never refers to herself by her name, but rather what that name was associated with, and she does so with very specific tenses. She <em>was</em> once part of Swaddle Dog, but <i>is</i> one of the Vuvalini. Her initiate mother <em>was</em> K.T. Concannon, but she still <i>is</i> the daughter of Mary Jabassa. She talks as if she has outgrown her childhood culture of Swaddle Dog – she had to for the sake of survival – but she still talks as one of the Many Mothers, and as if she still wishes to be associated with and accepted into this group she still cares for (present tense phrases). Seeking reaffirmation, she hopes to show that she is still selfless in the cause of the group and the people within it, because without them, Furiosa’s name means nothing to her. Elucidating on her combat experience, one could only imagine that her inability to bear children is why she was selected to become the inevitable driver of the War Rig, and how she lost her arm. <em>Fury Road</em>, within the first 5 minutes, before the title card, makes sure to establish norms and the social constructs that govern Immortan Joe’s Citadel, and from the very start, women have been boiled down to a single purpose: fertility. Her being assigned under the command of an existing Imperator would connect a lot of the scenes to losing an arm in battle, driving the War Rig in the first place, and how she is able to be so prepared for combat. Take the scene when Max, still muzzled and enchained to Nux, Furiosa is able to take down Max, be more than dominant at close quarters combat with a wrech, disarm Max of his shotgun, pull out a secret handgun on Max, while also preemptively pulling the kill switches on the War Rig as well so that even if Max proved victorious in their small skirmish, he couldn’t steal the resources. Not to mention the amount of firearms Furiosa stashes in the War Rig that Max reveals immediately after their scuffle, and her experience with a sniper rifle to take out the Bullet Farmer later during the night chase. There’s no way in her 20 years she could have advanced nearly as far as she could have without already being valued by a highly ranked member in society, as we by see the number of War Boys forced to conform to that initial ranking and die in battle, or grow only to the extent of the military’s drum corp. It is difficult to connect the Wives and Furiosa, other than the fact that Furiosa was at one point almost inducted into the group of prized breeders. We know Immortan Joe trusted Furiosa immensely for executing his water, bullet, and resource runs that extended beyond the Citadel, holding upwards of 3000 gallons of the prized resource “guzzoline” plus a surplus of water at a time. For how much of the Citadel he constantly monitored, to extend someone beyond his immediate control, and even reallocate some power and influence to someone else speaks immensely of the trust he bestowed unto Furiosa. So, for the fact that she’s a powerful commanding officer, and has a non-insignificant connection to the Wives indicates that is how she got in touch with them, and how she communicated her plan to smuggle them out as well. After she escapes the Citadel, we are now well into the film’s plot, and concludes the biography.</p>
<hr>
<p>While the above looked at three specific presences within the film, the three below are a series of more opinionated pieces discussing some of my favorite sticking points.</p>
<hr>
<h3 id="favorite-shot">Favorite Shot</h3>
<p>My favorite shot in <em>Mad Max: Fury Road</em> occurs for only a few frames during the Rock Riders chase scene after Furiosa’s exchange with them went south (this shot is one that I don’t think I consciously took in until my 2nd or 3rd viewing of the movie). They are well into the chase at this point with the Rock Rider’s signature bikers attacking the War Rig at all angles: explosives from the side, bikes jumping over the War Rig, armed bikers firing rounds whenever the can, all the meanwhile Immortan Joe in his Dodge Fargo 1940 “BigFoot” monster truck is catching up to them from the rear. In a moment of panic and without weapon, Furiosa lunges into her arsenal and grabs some kind of pistol from the bag, and in a single movement, lines up her shot alongside Max at a Rock Rider angling themselves along the side of their vehicle. This shot is only a few frames in length, but communicates so much about the character development of both Max and Furiosa and the relationship between them. We can actually map out their entire relationship visually from strangers, to foe, to forced allies, to tight-knit friends. You can see that they are strangers when they never share a frame; for the first part of the movie, there is usually a cut, or shift in lens focus to direct the audience’s attention to either Max <i>or</i> Furiosa, neither at the same time. They become foes at their first interaction after the sandstorm, and this is clearly indicated via their exchange of weapons. Furiosa attempts to shoot Max with his own shotgun, and moments later, Max threatens to shoot Furiosa with her own pistol. This helps emphasize the turbulent power dynamic between the two: they are both just as capable, but are perceiving each other as threats, so they continue to try and disarm each other, and inevitably turn one’s own weapon against them. This continues in the following scenes where they become reluctant partners, driving the War Rig together. Since Furiosa is the only one who can drive the War Rig, she seems to be in control of the situation. But, the first thing Max does before the War Rig departs is take and hold hostage every single last gun compartmentalized throughout the vehicle, bringing the power dynamic back into his favor. It’s similar to the back and forth they had as enemies, but now instead of being a constant duel of competitors, it’s now more of a dance of adversaries: they both want to accomplish different goals and have different ideas in mind separate from one another, but are both tense as they both potentially act as a threat to that success if they choose to act on it, almost like mutually assured destruction – one party stops another also forces to stop themselves. This is a change from the previous relationship where they both saw each other as direct impediments that are competing for the same goal, but they now realize that their ideas aren’t mutually exclusive. So, as unlikely companions, Max doesn’t kill Furiosa, but completely disarms her. This tension eventually gets alleviated as the two are both placed in precarious situations, and Max ultimately returns a weapon to her to help defend the crew, visually showing the trust building. Now, the shot I picked as my favorite is where the two are finally visually cued into being equals to one another: capability-wise, trust-wise, and as trusted allies. In those few frames, showing the two both aim at a single target together in the same shot is all it took for this film, with minimal dialogue between the characters, to graphically establish their relationship. I also really like it <em>because</em> of how short it is: it forces us, the audience, to passively take in the shot which helps us to understand the two characters are now strongly bonded without forcing their ever changing connection and feeding it to us directly. These cues allow us to take in a lot of information very quickly, and this is one of the best examples the film offers for how it does so with such a nuanced topic like character interaction.</p>
<h3 id="favorite-line">Favorite Line</h3>
<p>My favorite line in <em>Mad Max: Fury Road</em> is one of Furiosa’s final lines of the film during the final action sequence in which the protagonists end Immortan Joe’s corrupt rule. As Furiosa forces her way up to the driver’s side window to finally kill Immortan Joe, she delivers a final send off before he lashes out one last scream: “Remember me.” It twists the War Boys fabled motto, “Witness me!”, that they call before attempting a suicide act in an effort to be permitted into Valhalla under Immortan Joe’s servitude by giving their life in noble act of war. This phrase, “Witness me!”, evokes a tone of acknowledgement of the action; a phrase that asks for those who know they have already died to do so. It holds a connotation that what is being seen is merely recognized, but not appreciated, and that’s due in part by what the purpose of “witness” is: it’s an act to better oneself into the salvation of Valhalla, which they celebrate in normalizing their expendability of their current life and to carry on into an uncertain next. Furiosa’s spin on the phrase reverses that tone completely by saying “remember” instead of “witness”, which instead of asking for acknowledgement and self-betterment, is asking for gratitude. While Furiosa isn’t the one who physically dies, and Immortan Joe doesn’t physically survive, it makes sense to view it symbolically as if that was the way the scene was framed. By perceiving as so, it turns the messaging around by asking “Immortal” Joe to live on forever with full knowledge that she is who restored the world with the amount of sacrifices she had to endure; she’s asking not to “die” in vain, but to live in memory of those she has worked so hard to help. While it has the exact same physical outcome that the old, willing sacrifices that were “witnessed” had, it changes the mentality and respect surrounding those who may not have had a choice in their death to truly internalize the impact it had on those who had beared the trauma of the death in question.</p>
<p>This expression also immediately sets the ideology she seeks to replace Immortan Joe’s society with: people aren’t objects to watch be expended, but they are intelligent beings who deserve to forever live by their accomplishments and compassion they have shared for others beyond their self-interest. What makes this specific sentiment especially powerful is that the only memory that Immortan Joe would have to remember Furiosa by is <em>her own</em> exploitation that he leveraged, so by executing him with that memory is an extremely clear indicator that she wants those memories and experiences to die with him so no other person has to suffer through it and pushing her own abuse behind her. It’s Furiosa climactic developmental moment: just as Max gave his name to Furiosa to accept his <em>past</em>, Furiosa buries her past to accept her new <em>future</em>. She wants to have Immortan Joe explicitly know that he was the one who “killed the world” by destroying the very world he has built upon abuse and denigration with ending his life. The final component of this line that makes it so inspiring is coupled with the next important line that Nux so emotionally delivers: “Witness me.” The very phrase that Furiosa has reformed dies gently with Nux, the transitory character that was once a War Boy, now Vuvalini takes the cursed connotation of the phrase “witness” and completely transforms it to accommodate his developed moral enlightenment. Nux, for his whole life, has been told that the world doesn’t care for him, but he cares for the world; the Citadel will continue to run with the powerful machines that they worship, and they are merely the small, insignificant cogs in a social machine. Even though they are aware they are “kamakrazee”, they know that their life has no more meaning than what Immortan Joe provides. But by the end, after all he’s undergone and tolerated, he pours all of his new found emotion Furiosa has modelled throughout their adventure into his delivery, completely dropping his trochaic-accented meter of the War Boys’ chants, remnant of the famous Gregorian chant of death, Dies irae, before burying the last of the phrase along with the remaining scraps of Immortan Joe’s convoy, influence, and power. He knew he would die, and that there was no Valhalla for him to seek, but he hopes that him accepting a willing death for those he loves would be remembered beyond just a glorified suicide to the group, but someone of a friend. That last utterance of “witness” gives the very contrast needed to emphasize the importance of Furiosa’s choice of wording.</p>
<p>“Remember me!” is such a powerful line as it reverses the very sentiment that Immortan Joe terribly exploited back onto him, while also completely rebuilding a new tone and society within just those two words to break down what we, the audience, have been conditioned to hear so frequently that normalized death to respect its consequences and implications beyond a single use case. Furiosa, in just a few syllables, was able to take an entire society, destroy it, rebuild it, and accept her sacrifices for it.</p>
<h3 id="theme">Theme</h3>
<p><em>Mad Max: Fury Road</em> contains many broad, strongly supported topics of discussion, one of which includes a central thematic subject that revolves around how redemption is a self-realizing process that cannot be induced forcibly by a person, place, or material object, but can be conducted through one as a medium to enlighten oneself beyond past perception. </p>
<p>Similar to the analysis of the ended above, every major character follows an arc in which their persona is fleshed out such that they are able to newly perceive their life and how they fit into the events that they have been witness to. Continuously, the film, almost forcefully, imposes redemption as a subject matter. The first instance that redemption appears as a focus is within some of Immortan Joe’s first lines: “I am your redeemer! It is by my hand you will rise from the ashes of this world!” Many of his War Boys buy into this false ideology and into the notion that their salvation will be presented as an action that Immortan Joe provides directly to them. Max and Nux learn this first hand: literally being abandoned in the aftermath of a sandstorm, and symbolically “rising from the ashes” that Immortan Joe has incited with his chase of Furiosa. They then go on through their redemption arc (Nux’s arc won’t enter a phase of redemption until further into the film), but this scene helps to recontextualize Immortan Joe’s previous dialogue to fit the theme described. It wasn’t Immortan Joe who presented them with their redemption, but it was he whose hand presented the <em>opportunity</em> to redeem themselves; he was merely the objective that awarded redemption, not salvation himself. Another clear instance of the film’s portrayal of redemption is via Furiosa, with her deeply intimate and revealing conversation with Max, moments before her reunion with the Vuvalini. It’s here where she unveils not only why she’s seeking the Green Place for herself but for the others as well: </p>
<blockquote>
<p>“And [the Wives]?” </br>
“They’re looking for hope.” </br>
“And you?” </br>
“...Redemption.” </br></p>
</blockquote>
<p>This distinction is important as it aids in differentiating the purpose of the Green Place between the Wives and Furiosa. The Wives specifically are holding onto seeking something material — something tangible that directly impacts their life to separate them from Immortan Joe’s exploitation. They need that promise to believe in a life worth living. Furiosa, on the other hand, has a much deeper connection to the Green Place. It was her home that she was extracted from, enslaved at the hands of the very force she was trained to avoid: men. Knowing the trauma her people had to endure along with the acts she deeply laments serving Immortan Joe, Furiosa desires to repent and atone for, which she tries to do through helping the Wives and restoring herself to the Vuvalini. In the end, Furiosa does find acceptance and redemption, it doesn’t come without cost: nearly all of the Vuvalini die in her and the Wives’ names, reiterating how there isn’t manifestations of redemption that one can possess or know to enter a new state, but there are certain people and objects that can help guide one through their self-solace, because if that wasn’t true, the ending of <em>Fury Road</em> would have almost no impact; Furiosa’s story wouldn’t have a chance to resolve with the lack of the Vuvalini present, and Max’s leaving would make even less sense, as he is then literally abandoning his redemption, which is his most overarching plot motivator that has guided him through the film. </p>
<p>This is even reiterated in the music scoring for the film. When listening to the track labelled, “Redemption”, which plays during the previously described scene of Furiosa’s personal conversation with Max on their way to the Vuvalini and the Green Place. In it, a certain leitmotif is established along with a very distinct tone. However, in the following scene’s track, “Many Mothers”, it takes the redemption leitmotif that “Redemption” established, but emboldened with a fuller orchestration, connecting the theme to the scene. Similarly, during the blood transfusion scene where Max desperately tries to save Furiosa from dying of blood loss, his associated track, “My Name is Max”, it also contains the same leitmotif, but this time emphasizing rests and silence to allow room for the music to breathe and react to Max’s dialogue, especially his key titular line the track has been named for. If we were to take the connection in musical theme and apply it to the idea that redemption is something that can be contained within a person or group of people, like Max and the Vuvalini — characters who either left or died — then it would only reiterate the aforementioned theory that <em>Fury Road</em> along with many of its characters would remain unresolved, and the conclusion would have no significance nor impact that they movie clearly tried to convey. It’s more reasonable that the connection between “Redemption” and “Many Mothers” as well as “My Name is Max” is that it is used to represent the action that transpired <em>through or from</em> the relevant characters, permeating long after their presence with the others. They conducted and induced their redemption, albeit via different mediums, they are the ones who incited the redemption themselves, instead of being given it, or attained it via a sudden acquisition of someone or something.</p>
<p>There are many other examples, especially with Nux and his relationships between Capable and Max that exemplify the versatility and omnipresent nature of this theme of the film, these are some of the most distinct examples that elucidate Miller’s conveyance of the nature of redemption, and its intrinsically self-realizing and growing process.</p>
]]></description>
         <link>http://xperimex.github.io/blog/mad-max</link>
         <guid isPermaLink="true">http://xperimex.github.io/blog/mad-max</guid>
         <dc:creator><![CDATA[Adi Mittal]]></dc:creator>
      </item>
      <item>
         <title><![CDATA[Fixed Points and Fantastic Plots]]></title>
         <description><![CDATA[Stability amidst the chaos 

 <h2 id="introduction">Introduction</h2>
<p>Let me propose a question to start. Try to solve the following:</p>
<center>
<!-- $\fbox{ -->
  $\large{x^{x^{x^{x^{.^{\hspace{.07cm}.^{\hspace{.07cm}.}}}}}} = 2}$
<!-- }$ -->
</center>

<p>An infinite power tower which supposedly equals 2? Seems unlikely, but those familiar with these infinite-operation type problems likely know the strategy to solve this. Notice how there&#39;s a copy of our equation stacked on top of itself.</p>
<center>
  <!-- $\large{\fbox{$x^\fbox{${x^{x^{x^{.^{\hspace{.07cm}.^{\hspace{.07cm}.}}}}}}$}$} = 2}$ -->
  $\large{x^\fbox{${x^{x^{x^{.^{\hspace{.07cm}.^{\hspace{.07cm}.}}}}}}$} = 2}$
</center>

<p>Since we know that equation in the box is equal to 2 because it&#39;s a duplicate of our original equation, we can easily reduce the problem down to something much more manageable.</p>
<center>
$\large{x^2 = 2} \rightarrow x = \sqrt{2}$
</center>

<p>So, raising $\sqrt{2}$ to itself over and over again equals 2. What other equations can we solve? Let&#39;s try this one.</p>
<center>
$\large{x^{x^{x^{x^{.^{\hspace{.07cm}.^{\hspace{.07cm}.}}}}}} = 4}$
</center>

<p>Using the same strategy as before, this one is trivial.</p>
<center>
$\large{x^4 = 4} \rightarrow x = \sqrt[4]{4} = \sqrt{2}$
</center>

<p>Which is… the same answer as before? How can $f(x) = \sqrt{2}^x$ iterated over itself equal both 2 and 4 at the same time? When in doubt, we can ask our calculator for some confirmation.</p>
<h2 id="estimation-with-python">Estimation with Python</h2>
<p>With some simple Python, we can get a pretty good approximation quickly.</p>
<p><!-- HTML generated using hilite.me --><div style="background: #272822; overflow:auto;width:auto;border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em; font-size: 11pt;"><pre style="margin: 0; line-height: 125%"><span style="color: #f92672">import</span> <span style="color: #f8f8f2">math</span>
<span style="color: #66d9ef">def</span> <span style="color: #a6e22e">f</span><span style="color: #f8f8f2">(x):</span>
    <span style="color: #f8f8f2">temp</span> <span style="color: #f92672">=</span> <span style="color: #f8f8f2">x</span>
    <span style="color: #66d9ef">for</span> <span style="color: #f8f8f2">i</span> <span style="color: #f92672">in</span> <span style="color: #f8f8f2">range(</span><span style="color: #ae81ff">1000</span><span style="color: #f8f8f2">):</span>
        <span style="color: #f8f8f2">temp</span> <span style="color: #f92672">=</span> <span style="color: #f8f8f2">math</span><span style="color: #f92672">.</span><span style="color: #f8f8f2">sqrt(</span><span style="color: #ae81ff">2</span><span style="color: #f8f8f2">)</span><span style="color: #f92672">**</span><span style="color: #f8f8f2">temp</span>
    <span style="color: #66d9ef">return</span> <span style="color: #f8f8f2">temp</span>
<span style="color: #f8f8f2">print(f(</span><span style="color: #ae81ff">1</span><span style="color: #f8f8f2">))</span>
</pre></div></p>
<p>The above code creates and evaluates a power tower 1000 numbers tall, giving us an approximation of <code>2.0000000000000004</code>, which is pretty close to 2. So, is 4 anywhere to be seen? Actually, yeah; our solution wasn&#39;t <em>completely</em> false. Notice that at the end of the script it says <code>f(1)</code>. That 1 is our <em>seed value</em>. Since our power tower can&#39;t be infinite in order to get a calculable approximation, we need to cut it off after some amount (in this case, 1000 numbers high). In order to do that, though, there has to be some number there at the top of that power tower. In this case it was 1, but it can be anything as we constantly plug our output back into our input, in the case of an infinitely stacked power tower, that seed value is negligible. Let&#39;s see what happens if that is changed to <code>f(4)</code>.</p>
<p><!-- HTML generated using hilite.me --><div style="background: #272822; overflow:auto;width:auto;border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em; font-size: 11pt;"><pre style="margin: 0; line-height: 125%"><span style="color: #f8f8f2">print(f(</span><span style="color: #ae81ff">4</span><span style="color: #f8f8f2">))</span>
</pre></div></p>
<p>Due to rounding, our script actually blows up to infinity with <code>f(4)</code>, but we can reason this out by hand. If we start with 4, then our first output of iteration will be $\sqrt{2}^4 = 4$. Since 4 is our output, that&#39;s our new input. But since 4 was also our seed value, it&#39;ll just constantly output 4 at every iteration. So 4 <i>is</i> a convergent value (as we can only calculate finite approximations) to the infinite power tower of $\sqrt{2}$, but only for its seed value. To better understand this, we can use a tool known as a <em>cobweb plot</em>.</p>
<h2 id="cobwebs">Cobwebs</h2>
<p>Cobweb plots are a simple, elegant method to model iterative functions in the Cartesian plane by utilizing a seemingly mundane auxiliary function: $y = x$. What is probably the first graphs people are taught in elementary school is one of the most helpful in modeling these complicated and  otherwise impossible to view functions. Here&#39;s how to make a cobweb plot: 1) Plot the function to be iterated on (in this case, $f(x) = \sqrt{2}^x$) and $y = x$ together. 2) Pick a seed value to start iterating on. 3) Alternately draw vertical and horizontal lines within bounds of each graph for as many iterations as one needs. Steps 1 and 2 should be clear enough as they&#39;re fairly similar to what we did above, but Step 3 might need a visual to go along with it.</p>
<p>Here&#39;s the first step&#39;s resulting plot:</p>
<p><img src="/img/fixed-points/cobweb1.png" style="width:500px; height=auto "></p>
<p>Nothing too crazy. The green graph is our $f(x) = \sqrt{2}^x$, while the red graph is our $y = x$. For Step 2 we&#39;ll pick $x = 1$ as our seed value as we did before. This is where the magic of Step 3 comes in: from $x = 1$, we&#39;ll draw a vertical line from the red graph until it intersects at the green graph.</p>
<p><img src="/img/fixed-points/cobweb2.png" style="width:500px; height=auto "></p>
<p>Now we have a line segment with points $(1,1)\rightarrow(1,f(1))$. This step is equivalent to plugging in 1 into the top of our power tower, geometrically doing the operation of $f(x)$. Since we just a drew a vertical line, we now draw a horizontal one from the green graph $f(x)$ until it intersects the red one $y = x$.</p>
<p><img src="/img/fixed-points/cobweb3.png" style="width:500px; height=auto "></p>
<p>Now we have a new line segment from $(1,f(1))\rightarrow(f(1),f(1))$. You can probably see where this is going. Now that we have a new point at $x = f(1)$, we can draw a new vertical line until it hits the green graph, geometrically finding the value of $f(f(1))$, performing our repeated operation! We can do this series of horizontal to vertical lines as many times as we want to get as many iterations of our repeated function as we want!</p>
<p><img src="/img/fixed-points/cobwebFinal.png" style="width:500px; height=auto "></p>
<p>Now you can probably see why this is called a cobweb plot, as we weave back and forth creating a net-like shape between the graphs (and it only gets more wild looking with different iterative functions!). Even in the previous graph where I set the seed value to be $x=-1$, our graph still quickly hones in on evaluating to $x = 2$ for the $\sqrt{2}$ power tower, just where it happens to be the intersection of our two plots. This is a pretty narrow scope of our graph, though; let&#39;s zoom out and see more of this plot.</p>
<p><img src="/img/fixed-points/cobwebZoom.png" style="width:500px; height=auto "></p>
<p>There&#39;s also an intersection at $x=4$! Even with all of this, I don&#39;t think it would be wrong to feel that $x=4$ should <em>not</em> be a solution to some extent. Even though, it clearly shows a lot of the same characteristics that $x=2$ does, it still feels weird for this to be considered an answer, or at least to the same extent that $x=2$ is. For any seed $x&lt;4$, our iteration converges to $x=2$, and for any $x&gt;4$, it diverges. Only at $x=4$ does our repeated power tower equal 4. To properly understand this, we&#39;ll need to utilize derivatives.</p>
<h2 id="derivatives-and-sensitivity">Derivatives and Sensitivity</h2>
<p>The classic definition of the derivative $f&#39;(x)$ is a function that returns the slope of $f(x)$ at every point $x$. While this definition of the derivative isn&#39;t wrong, it is fairly limiting when only considered in the contexts of slopes. We can reframe the idea of a derivative not to be the slope of a function at a point $(a,f(a))$ but rather how <em>sensitive</em> the function is at the point $(a,f(a))$. This will be more apparent if we plot our $f(x)=\sqrt{2}^x$ in a new way.</p>
<p><img src="/img/fixed-points/newGraph.png" style="width:700px; height=auto "></p>
<p>You can generate the above plot with the following Python:</p>
<p><!-- HTML generated using hilite.me --><div style="background: #272822; overflow:auto;width:auto;border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em; font-size: 11pt;"><pre style="margin: 0; line-height: 125%"><span style="color: #f92672">import</span> <span style="color: #f8f8f2">numpy</span> <span style="color: #66d9ef">as</span> <span style="color: #f8f8f2">np</span>
<span style="color: #f92672">import</span> <span style="color: #f8f8f2">matplotlib.pyplot</span> <span style="color: #66d9ef">as</span> <span style="color: #f8f8f2">plt</span></p>
<p><span style="color: #66d9ef">def</span> <span style="color: #a6e22e">f</span><span style="color: #f8f8f2">(x):</span>
  <span style="color: #66d9ef">return</span> <span style="color: #f8f8f2">np</span><span style="color: #f92672">.</span><span style="color: #f8f8f2">sqrt(</span><span style="color: #ae81ff">2</span><span style="color: #f8f8f2">)</span><span style="color: #f92672">**</span><span style="color: #f8f8f2">x</span>
<span style="color: #f8f8f2">inp</span> <span style="color: #f92672">=</span> <span style="color: #f8f8f2">np</span><span style="color: #f92672">.</span><span style="color: #f8f8f2">linspace(</span><span style="color: #f92672">-</span><span style="color: #ae81ff">5</span><span style="color: #f8f8f2">,</span><span style="color: #ae81ff">5</span><span style="color: #f8f8f2">,</span><span style="color: #ae81ff">40</span><span style="color: #f8f8f2">)</span>
<span style="color: #f8f8f2">out</span> <span style="color: #f92672">=</span> <span style="color: #f8f8f2">[f(n)</span> <span style="color: #66d9ef">for</span> <span style="color: #f8f8f2">n</span> <span style="color: #f92672">in</span> <span style="color: #f8f8f2">inp]</span>
<span style="color: #f8f8f2">d</span> <span style="color: #f92672">=</span> <span style="color: #ae81ff">10</span></p>
<p><span style="color: #f8f8f2">fig</span> <span style="color: #f92672">=</span> <span style="color: #f8f8f2">plt</span><span style="color: #f92672">.</span><span style="color: #f8f8f2">figure(figsize</span><span style="color: #f92672">=</span><span style="color: #f8f8f2">(</span><span style="color: #ae81ff">20</span><span style="color: #f8f8f2">,</span><span style="color: #ae81ff">4</span><span style="color: #f8f8f2">))</span>
<span style="color: #f8f8f2">axes</span> <span style="color: #f92672">=</span> <span style="color: #f8f8f2">plt</span><span style="color: #f92672">.</span><span style="color: #f8f8f2">gca()</span>
<span style="color: #f8f8f2">axes</span><span style="color: #f92672">.</span><span style="color: #f8f8f2">set_xlim([</span><span style="color: #f92672">-</span><span style="color: #ae81ff">5.3</span><span style="color: #f8f8f2">,</span><span style="color: #ae81ff">5.3</span><span style="color: #f8f8f2">])</span>
<span style="color: #f8f8f2">axes</span><span style="color: #f92672">.</span><span style="color: #f8f8f2">set_ylim([</span><span style="color: #f92672">-</span><span style="color: #ae81ff">6</span><span style="color: #f8f8f2">,</span><span style="color: #ae81ff">6</span><span style="color: #f8f8f2">])</span></p>
<p><span style="color: #f8f8f2">plt</span><span style="color: #f92672">.</span><span style="color: #f8f8f2">scatter(inp,</span> <span style="color: #f8f8f2">[d</span><span style="color: #f92672">/</span><span style="color: #ae81ff">2</span> <span style="color: #66d9ef">for</span> <span style="color: #f8f8f2">n</span> <span style="color: #f92672">in</span> <span style="color: #f8f8f2">range(len(inp))])</span>
<span style="color: #f8f8f2">plt</span><span style="color: #f92672">.</span><span style="color: #f8f8f2">scatter(out,</span> <span style="color: #f8f8f2">[</span><span style="color: #f92672">-</span><span style="color: #f8f8f2">d</span><span style="color: #f92672">/</span><span style="color: #ae81ff">2</span> <span style="color: #66d9ef">for</span> <span style="color: #f8f8f2">n</span> <span style="color: #f92672">in</span> <span style="color: #f8f8f2">range(len(out))])</span>
<span style="color: #66d9ef">for</span> <span style="color: #f8f8f2">n</span> <span style="color: #f92672">in</span> <span style="color: #f8f8f2">range(len(inp)):</span>
  <span style="color: #f8f8f2">plt</span><span style="color: #f92672">.</span><span style="color: #f8f8f2">plot([inp[n],</span> <span style="color: #f8f8f2">out[n]],</span> <span style="color: #f8f8f2">[d</span><span style="color: #f92672">/</span><span style="color: #ae81ff">2</span><span style="color: #f8f8f2">,</span> <span style="color: #f92672">-</span><span style="color: #f8f8f2">d</span><span style="color: #f92672">/</span><span style="color: #ae81ff">2</span><span style="color: #f8f8f2">],</span> <span style="color: #f8f8f2">color</span><span style="color: #f92672">=</span><span style="color: #e6db74">&#39;green&#39;</span><span style="color: #f8f8f2">)</span>
</pre></div></p>
<p>This basically just took the $y$-axis of our Cartesian graph and rotated it $90^\circ$. The blue dots represent the preimage of points $x$, while the orange dots represent their associated transformations under $f(x)$ with green lines connecting them. Just looking at it, it&#39;s consistent with our Cartesian graph as $f(x)$ never goes below 0, which makes sense as an exponential is always positive. The reason why we want this graph as it guides the intuition behind this idea of sensitivity and the derivative.</p>
<p>Notice the dots around $x=-3$ in the preimage (blue) points. They all get mapped and squished down near $.354$ under $f(x)$; they get tightly pressed together. But just <em>how</em> tightly pressed together are they? That&#39;s exactly what the derivative tells us! For a small change $dx$, we want to know how much that changes the output $df$. In this case, $f(x)=\sqrt{2}^x \rightarrow f&#39;(x)=\sqrt{2}^x\cdot\ln{\sqrt{2}}$. Plugging in $f&#39;(-3)=.1225$. This means that around $x=-3$, the ratio between how much the points around it changes under $f(x)$ is $.1225$, in other words, the area around $x=-3$ appears to have shrunk <em>inward</em> by a factor of $.1225$. In the contexts of slopes, this ratio would be the slope of our tangent line, telling us how tall $df$ would be relative to $dx$. Since the derivative $f(-3)$ is small, we can say that $f(x)$ is not very sensitive around $x=-3$, as a small change in input from $-3$ will still evaluate to about the same value.</p>
<p>Now let&#39;s look on the right half of the graph. Trying $f&#39;(4.5)=1.6486$ would imply under our previous logic, that we&#39;d expect points to stretch <em>away</em> from $x=4.5$ by a factor of $1.6486$. Just by looking at our plot, that&#39;s not so hard to believe. This means that our $f(x)$ is sort of sensitive around $x=4.5$, as a small difference in input from $4.5$ can lead to a big difference in evaluating $f(x)$.</p>
<p>So now we know that for a given $a$, if $|f&#39;(a)| &lt; 1$, it&#39;s a shrink, and if $|f&#39;(a)| &gt; 1$, it&#39;s a stretch (a negative derivative implies there&#39;s also a flip occurring, but we care only about magnitude). You can now kind of imagine what effects these have when we iterate over $f(x)$ for a long time: points will gravitate towards numbers that shrink the area around them, and be repelled away from numbers that stretch them. Now, relating this back to our original Cartesian plot, let&#39;s highlight the areas in which $|f&#39;(a)| &gt; 1$.</p>
<p><img src="/img/fixed-points/derivativeGraph.png" style="width:500px; height=auto "></p>
<p>Well, look at that! Our $x=4$ solution is in our blue $|f&#39;(x)|&gt;1$ region, while our $x=2$ solution is not!</p>
<p>Connecting this all together now, we had two solutions to an iterative function, but only one of which was appearing in practically every case. When graphing its respective cobweb plot, we see that one solution lies in a non-sensitive region ($f&#39;(2) = .6931$), while the other does ($f&#39;(4) = 1.3863$). So what can we say about either solution? Since we know $f(2)$ is not sensitive to small changes and moreover shrinks space around it, we know that $x=2$ is a <strong>stable fixed point</strong> of the iterative function $f(x) = \sqrt{2}^x$. It&#39;s stable under the notion that because it isn&#39;t sensitive to small changes in its neighborhood of points, with each iteration we take, we map points closer and closer to $x=2$ due to the squishing effect of its derivative. But for $x=4$, which is sensitive, each iteration tends to stretch and repel points away from $x=4$, even though it too intersects in our cobweb plot as well as analytically solves the equation. Hence, we call $x=4$ an <strong>unstable fixed point</strong> of the system. Just like we&#39;ve described, while $x=4$ is valid for its seed value, the slightest discrepancy in value pushes numbers away from it to either start approaching $x=2$, or diverge to infinity (like in our rounding error in the Python script before!). If we quickly go back to our graph style with 2 number lines and perform the function iteratively there, we can really see what these pulls and pushes of numbers looks like. Here&#39;s what the first 10 iterations of $\sqrt{2}^x$ looks like:</p>
<p><img src="/img/fixed-points/iterativeGraph.png" style="width:700px; height=auto "></p>
<p>You can really see how tight the points coil around $x=2$, and split away from $x=4$. Even with an initial value that starts so close to $x=4$, you can still see it slightly drift away from it at each iteration. This is why thinking of derivatives as measures of sensitivity is so important: the value of the derivative tells you how strong of a pull or push certain numbers have. Consistent with our findings, $x=2$ has a pulling effect around it with a small derivative, while $x=4$ has a pushing effect with its large derivative.</p>
<p>This is why we were also able to use cobweb plots: they were the geometric algorithm to solve when $f(x)=x$, which makes sense as if something is a fixed point, no matter how many times we apply a function to it, it should remain the same. So when solving $\sqrt{2}^x = x$, you&#39;ll get the intersections we found earlier at $x=2,4$ (if you want to try and actually solve this equation, it requires the clever use of the <a href="https://mathworld.wolfram.com/LambertW-Function.html">Lambert W-function</a>). That&#39;s why we were able to analytically solve for two different solutions, but only one kept popping up everywhere. This isn&#39;t limited to just power towers, though.</p>
<h2 id="variations">Variations</h2>
<p>This type of relationship between stable and unstable fixed points is everywhere. Take the well-known infinite fraction below:</p>
<center>
$1 + \large{\frac{1}{1 + \frac{1}{1 + \frac{1}{1 + \frac{1}{\ddots}}}} }$
</center>

<p>By setting this equal to $x$, we can solve it just like we did before with the power towers.</p>
<center>
$1 + \large{\frac{1}{ \fbox{$1 + \frac{1}{1 + \frac{1}{1 + \frac{1}{\ddots}}} $} }} = x$
<br>
$1 + \frac{1}{x} = x$
<br>
$x^2-x-1=0$
</center>

<p>Using the quadratic formula, we once again get two solutions:</p>
<center>
$\varphi = \frac{1+\sqrt{5}}{2} \approx 1.618$ and $1-\varphi = \frac{1-\sqrt{5}}{2} \approx -.618$
</center>

<p>The famous Golden ratio $\varphi$ and its underrated second solution. Still, it begs the question, how can a completely positive infinite fraction equate to something negative? Illustrating this with our cobweb and sensitivity regions will make this clear once again. Setting $f(x)=1+\frac{1}{x}$, we get…</p>
<p><img src="/img/fixed-points/cobwebGolden.png" style="width:500px; height=auto "></p>
<p>A lot like $x=4$ when iterating $\sqrt{2}^x$, $1-\varphi$ is the unstable fixed point in the sensitive region, with numbers getting pushed away at every iteration, while $\varphi$ is the stable one which we quickly spiral down towards. We can quickly verify that $1-\varphi$ is a &quot;valid&quot; solution by plugging it into $1+\frac{1}{x}$ just like we did with $x=4$ into $\sqrt{2}^x$.</p>
<center>
$1+\frac{1}{1-\varphi} = 1-\varphi$
</center>

<p>For its own seed value, $1-\varphi$ is valid, but I guess that&#39;s up to you if you want to equate a negative value to a positive infinite fraction.</p>
<p>For those who are interested, try setting your seed value to a number in the form of $-\frac{F_n}{F_{n+1}}$ where $F_n$ represents the nth Fibonacci number. The Golden ratio is closely tied to the Fibonacci numbers, so it may be a bit unsurprising why they may relate here. If you try to iterate over any number in this form, you&#39;ll eventually hit a point where evaluating the function becomes undefined. Try plugging in a few and watch the strange cascading effect happen.</p>
<p>There are a whole host of functions that have interesting iterations as well. Let&#39;s try $f(x) = \cos(x)$</p>
<p><img src="/img/fixed-points/cobwebCOS.png" style="width:500px; height=auto "></p>
<p>Since $f&#39;(x) = -\sin(x)$, $|f&#39;(x)|$ is always less than or equal to 1, so all fixed points it has will not diverge. In this case, we get a solution of $\approx .73909$, sometimes referred to as the <a href="https://mathworld.wolfram.com/DottieNumber.html">Dottie number</a>, which has its own set of interesting properties (for one, it&#39;s a transcendental number of the likes of $\pi$ and $e$!). If you are interested in a bit of why this has a fixed point, allow me to point you towards the <a href="https://en.wikipedia.org/wiki/Banach_fixed-point_theorem">Banach Fixed-Point Theorem</a> for an interesting perspective that guarantees this fixed point. Let&#39;s try another function. What happens if we scale $f(x)$? Let&#39;s try $5f(x) = 5\cos(x)$</p>
<p><img src="/img/fixed-points/cobweb5COS.png" style="width:500px; height=auto "></p>
<p>We have not one, not two, but three different intersection points of where $5\cos(x) = x$. But notice, all three of them lie within the sensitive region where $f&#39;(x) &gt; 1$; they&#39;re all unstable. You can probably tell just by looking at it, it&#39;s a very chaotic diagram. This might not be unexpected for some of you though. If it doesn&#39;t converge to anything, but also not diverge, why wouldn&#39;t it just randomly jump around ad infinitum? Well, let me just present another function to explain why. Let&#39;s make a cobweb plot for $f(x) = 3.2x(1-x)$</p>
<p><img src="/img/fixed-points/logisticMap.png" style="width:500px; height=auto "></p>
<p>Here we have 2 intersection points, both of which are in the sensitive region where points should not converge to excluding its own value, and that&#39;s exactly what we see with no definite attraction to any one fixed point. Yet, it&#39;s not like our iterations are randomly moving. In fact, just looking at the diagram, it&#39;s quite predictably going in a cycle between two $x$-values of $\approx .516$ and $\approx .8$. The difference between $5\cos(x)$ and $3.2x(1-x)$ is how it interacts with our seed value. For the former, it has a quality known as <em>sensitive dependence on initial conditions</em>, or more commonly referred to as the Butterfly effect: a small change in the seed value can produce wildly different outputs in iteration in the long run, just like how a butterfly&#39;s wings can produce a hurricane years later halfway across the globe. This is a common property of what is aptly deemed <em>chaotic behavior</em>. The latter function, while it may not have a convergent value, it does not exhibit Butterfly effect-esque behavior nor chaos while iterating over it, and instead settles into this cycle. As a kickstarter for those interested, $3.2$ in the latter function was not an arbitrary choice: it comes from a family of iterative functions of the form $rx(1-x)$ known as the <a href="https://mathworld.wolfram.com/LogisticMap.html">logistic map</a>. There&#39;s so much to talk about there, it likely will be its own post later, but that&#39;s for another day.</p>
<p>I want to go back to the Golden ratio problem as there&#39;s a neat extension to a more general case of an iterative approximation technique that can be more applicable to problem solving that I want to share. It is known as the <strong>Newton-Raphson Method</strong> which can (usually) effectively hone in on roots of a polynomial quite efficiently.</p>
<h2 id="newton-raphson-method">Newton-Raphson Method</h2>
<p>The idea is fairly similar to what we did before, but since it&#39;s catered to finding roots of polynomials, its iterations have a modified step as we&#39;re looking for intersections with the $x$-axis instead of the line $y=x$. Here&#39;s the basic idea: 1) Pick an initial seed value $x_0$. 2) Draw a vertical line (like we did with the cobweb) until we hit the function $f(x)$. 3) Draw the tangent line of $f(x)$ at $x_0$, and see where it hits the $x$-axis. Call this new point $x_1$. 4) Repeat the process as many times as you&#39;d like for as accurate an approximation as you&#39;d like up to some $x_n$. Here&#39;s an example geometric interpretation for this method with $f(x) = x^2 - 13$.</p>
<p><img src="/img/fixed-points/NR1.png" style="width:500px; height=auto "></p>
<p>I had to zoom in extremely close for this graph because, as you can see, just after two iterations from a seed value $x_0=5$ finds a really accurate approximation of one of the roots of $f(x)$ and you wouldn&#39;t be able to see those lines unless magnified by this much. Let&#39;s work out a general iterative formula for this method. We first start with some $f(x)$. Just by using derivatives and definition of a line passing through the point $(x_n,f(x_n))$ for our tangent, we can solve the equation</p>
<center>
$f&#39;(x_n)(x-x_n) + f(x_n) = 0$
</center>

<p>to find the next point $x_{n+1}$ to continue iterating on (as it should be the $x$-intercept of that line like the instructions describe). Doing some basic algebra shows that:</p>
<center>
$f&#39;(x_n)(x-x_n) + f(x_n) = 0$
<br>
$f&#39;(x_n)(x-x_n) = -f(x_n)$
<br>
$x = x_n - \frac{f(x_n)}{f&#39;(x_n)}$
</center>

<p>So, tidying things up, for a given (continuous and differentiable) function $f(x)$, we can approximate its roots by iterating over with some initial $x_0$:</p>
<center>
$x_{n+1} = x_n - \frac{f(x_n)}{f&#39;(x_n)}$
</center>

<p>Trying this out with our $f(x) = x^2 - 13$, our recurrence relation after some simplifying becomes</p>
<center>
$x_{n+1} = \frac{1}{2}(x_n + \frac{13}{x_n})$
</center>

<p>Or if you liked our previous notation, we can rewrite this as a function and iterate over</p>
<center>
$g(x) = \frac{1}{2}(x + \frac{13}{x})$
</center>

<p>Since this is in function form, we can use our old friend the cobweb to solve this for us.</p>
<p><img src="/img/fixed-points/cobwebSQRT.png" style="width:500px; height=auto "></p>
<p>It nicely finds $\sqrt{13}$ as a solution, just as we would expect. However, notice that there are two intersection points that lie <em>outside</em> of the sensitive region. One we found at $x=\sqrt{13}$, and the other is actually the second solution to $x^2-13=0$ at $x=-\sqrt{13}$. Our seed value significantly matters more in this case, as now depending on which zero of $f(x)$ is closer, our iteration will target only the closest solution, and this only becomes more important the more zeroes our function contains.</p>
<p>Even with all those caveats, notice what we just made! Our iterative function $g(x)$ is essentially a square root estimator, but with no exponents! While it&#39;s nice and convenient just to use exact answers, having decimal approximations are just as useful, especially for computers who don&#39;t have unlimited memory to use exact answers. For any number $n$, we can calculate $\sqrt{n}$ as accurately as we&#39;d like by iterating over the function</p>
<center>
$g(x) = \frac{1}{2}(x + \frac{n}{x})$
</center>

<p>as many times as we want. There are some exceptions where certain seeds can infinitely cycle or actually result in no subsequent $x_{n+1}$ (imagine a horizontal tangent line), but this method is incredibly useful, as this doesn&#39;t just extend to square roots, but to any function you want to approximate using the aforementioned formula</p>
<center>
$x_{n+1} = x_n - \frac{f(x_n)}{f&#39;(x_n)}$
</center>

<p>Here are a few other iterative functions for other roots of $n$:</p>
<center>
$\sqrt{n} \rightarrow \frac{1}{2}(x + \frac{n}{x})$
<br>
$\sqrt[3]{n} \rightarrow \frac{1}{3}(2x+\frac{n}{x^2})$
<br>
$\sqrt[4]{n} \rightarrow \frac{1}{4}(3x+\frac{n}{x^3})$
<br>
$\sqrt[p]{n} \rightarrow \frac{1}{p}((p-1)x+\frac{n}{x^{p-1}})$
</center>

<p>Going back to our Golden ratio iteration, we can rewrite it under the fixed point formula $f(x)=x\rightarrow 1+\frac{1}{x}=x$. If you multiply that through by $x$ and rearrange, we get a quadratic $x^2-x-1=0$. That&#39;s a quadratic we can solve for with the Newton-Raphson Method! Plugging it into the formula, we get a function to iterate over as</p>
<center>
$g(x) = \frac{x^2+1}{2x-1}$
</center>

<p>And sure enough, it works! The advantage of using the Newton-Raphson Method in this case, is that we no longer have to worry about unstable fixed points, as all of our solutions lie outside the sensitivity region. So even if we lose some insight into the nature of each solution, we consistently find each solution of $\varphi$ and $1-\varphi$ to an accurate decimal expansion with the right seed.</p>
<p><img src="/img/fixed-points/cobwebGolden2.png" style="width:500px; height=auto "></p>
<h2 id="what-else-">What Else?</h2>
<p>Iteration and fixed points become one of the prime topics for dynamical systems and describing much of the world around us. We discussed the Newton-Raphson Method of root finding, but there are many other recurrence relations for approximating roots of functions, each catered for their own purpose with different convergence rates and fail cases. Moreover, this is just a single <em>use</em> of the Newton-Raphson Method, for it is more well known as an alternative to gradient descent. Solving systems of differential equations comes down to finding the equivalent of a higher-dimensional fixed point, or in other words, an eigenvector: a vector (which is just an object that can encode more than one number and hence dimension) which doesn&#39;t change direction under the transformation describing the system of equations. Markov chains are also another extremely important occurence of fixed points over iteration: after a long series of transitions between states, we can make an overarching statement about the system as a whole reaching an <em>equilibrium state</em> where transition probabilities are expected to remain the same (going back to that idea of eigenvectors!). Synchronization is a prime example of a fixed point under iteration: even if a group of fireflies begin out of phase with one another, their coupling over time will reduce each other into a single large group with one cyclic, uniform behavior. The Mandelbrot set (and all of the Julia sets, for that matter) arise out of the fact that some complex numbers are bounded under iteration of functions $f(z)=z^n+c$ that remain bounded after a long time (sometimes being bounded to multiple values at once!). There are even entire studies dedicated to this. <em>Invariant theory</em> studies mathematical groups and polynomials to see how they remain unchanged under transformations. Almost all of chaos theory is about stability (or the lack thereof) over long periods of time (Nicky Case has a great introduction to <a href="https://ncase.me/attractors/">attractors</a>), and especially when what should be simple, predictable equations are not (we already talked about the logistic map, but see it illustrated in the <a href="https://en.wikipedia.org/wiki/Bifurcation_diagram">Bifurcation diagram</a>. It is particularly interesting for it appears in the most unlikely of places). We saw some chaotic behavior earlier, and the way I deduced it was chaotic was with a quantifier all iterative functions and maps have known as the <a href="https://en.wikipedia.org/wiki/Lyapunov_exponent">Lyapunov exponent</a>, and this itself is so interesting to look at for how functions change in behavior along with its Lyapunov exponent. For fixed points alone, there are hundreds of theorems dedicated to analyzing them (most notable of them being <a href="https://en.wikipedia.org/wiki/Brouwer_fixed-point_theorem">Brouwer&#39;s Fixed-Point Theorem</a>).</p>
<p>If you are interested in anything covered here, popular math YouTube channel <a href="https://www.youtube.com/channel/UCYO_jab_esuFRV4b17AJtAw">3Blue1Brown</a> made not <a href="https://youtu.be/CfW845LNObM">one</a> but <a href="https://youtu.be/elQVZLLiod4">two</a> videos discussing this idea of derivatives and infinitely stacked operations with the exact puzzle I posed at the start of this post. Their first video is what originally inspired me to look into these objects more when I first saw it a couple yeas back. Their animations do wonders compared to what any text post can do, so please do check them out if you want a more visual approach to these processes along with some additional justification for solutions to iterative processes.</p>
<p>Fixed points appear everywhere, and I hope this shared a few insights into how they can appear, deceive, and approximate even the most out there of expressions.</p>
]]></description>
         <link>http://xperimex.github.io/blog/fixed-points</link>
         <guid isPermaLink="true">http://xperimex.github.io/blog/fixed-points</guid>
         <dc:creator><![CDATA[Adi Mittal]]></dc:creator>
      </item>
      <item>
         <title><![CDATA[Metropolis-Hastings and MCMC, Briefly]]></title>
         <description><![CDATA[How to guess mathematically 

 <p>Today, I want to talk about a really powerful tool in math and statistics, that on its own may seem very niche, the concept behind it is something really—and I mean <em>really</em>—powerful and is how many other discoveries and tools are made and immortalized. In particular, I want to talk about the Metropolis-Hastings algorithm and Markov chain Monte Carlo methods. If you want to skip the basics, here&#39;s a short table of contents:</p>
<ol>
<li><a href="#markov-chains">Markov Chains</a></li>
<li><a href="#monte-carlo-simulations">Monte Carlo Simulations</a></li>
<li><a href="#metropolis-hastings-and-mcmc">The Metropolis-Hastings Algorithm</a></li>
</ol>
<p>Brief summaries are at the bottom of each section if you want a quick referesher for anything above, but first, some review.</p>
<hr>
<p>This is also all written more formally with other examples in this <a href="/img/metropolis-hastings/Metropolis_Hastings_and_MCMC.pdf">paper</a>.</p>
<h2 id="markov-chains">Markov Chains</h2>
<p><strong>Markov chains</strong>, in essence, are a way to model a process that randomly jumps between different outputs, where each output is said to have some probability to jump to other outputs. They&#39;re sort of like rolling dice, but the likelihood you roll any number is only dependent on the number you rolled last. It might help to describe this with an example. Let&#39;s say you want to know what the weather will be in 5 days: will it be sunny or rainy? Fortunately, the weather doesn&#39;t vary too much, so if it&#39;s sunny one day, it&#39;s likely to be sunny again the next day with 80% chance. If it&#39;s rainy, it will likely be rainy again too, with, say, 60% chance. This can be shown quite succinctly in a little diagram:</p>
<p><img src="/img/metropolis-hastings/markovChainExample.png"></p>
<p>This is our actual Markov chain, showing the two <strong>transition states</strong>, S(unny) and R(ainy) with their associated transition probabilities. However, we can&#39;t actually <em>do</em> much with just a picture alone. So, we can rewrite these probabilities and encode them in a matrix:</p>
<center>
$
M =
\begin{bmatrix}
.8 &amp; .2 \\
.4 &amp; .6
\end{bmatrix}
$
</center>

<p>You can think of each row as a different state for current weather, and the columns as probabilities for different states of tomorrow&#39;s weather. In this case, I have written row 1 and column 1 to indicate sunny days, and row 2 and column 2 to be rainy days. That&#39;s why entry $a_{1,1}$ in row 1, column 1 shows 80%, because if it is sunny today (row 1), we expect an 80% chance for it to be sunny tomorrow (column 1). Similarly $a_{2,2}=.6$, as if it&#39;s rainy today, we expect a 60% chance for rain again. $a_{1,2}=.2$ means that if today is sunny, then there is a 20% chance of rain tomorrow, and for completeness sake, $a_{2,1}=.4$ indicates a 40% chance for it to be sunny given today is rainy.</p>
<p>What we&#39;ve built here is known as a <strong>transition matrix</strong>, as, well, it&#39;s a matrix that shows transition probabilities; it&#39;s a matrix that shows how likely we are to jump from one state to another. In this case, our states are the different weathers: sunny or rainy. So, how does this help us answer our original question of the what the weather will be in 5 days? Well, let&#39;s first try to find the weather 2 days from now. We know how to model 1 day from now, and since these are probabilities, wouldn&#39;t it make sense just to multiply our matrix by itself?</p>
<center>
$
M^2 =
\begin{bmatrix}
.72 &amp; .28 \\
.56 &amp; .44
\end{bmatrix}
$
</center>

<p>Our probabilities have changed a little bit. Now it&#39;s saying, if today is sunny, there is a 72% chance it will be sunny 2 days from now. The reason why multiplying our matrix itself to get this result makes sense is because of the mechanics of matrix multiplication essentially asks: &quot;What is the probability from getting from one state to another in two steps?&quot; If you work out the multiplication itself, it might be clearer, but the way I like to think about it is in terms of transformations of space. For those familiar with a bit of linear algebra, we can think of our matrix $M$ as a collection of basis vectors that scale space (where our vectors in space can be thought of as a collection of starting states, i.e. the initial observed proportion of sunny days to rainy days). So applying $M$ once transforms space, we can then take that as a new &quot;default&quot; or &quot;unit&quot;. If we apply $M$ again to our basis vectors, it has the effect of transforming space once again. This can be thought of as our standard, independent probability multiplication, but instead of changing a singular probability (i.e. dice value), we are changing two (likelihood of sunny <em>and</em> likelihood of rainy days).</p>
<p>With this in mind, our question is easy. It boils down to what $M^5$ is.</p>
<center>
$
M^5 =
\begin{bmatrix}
.67008 &amp; .32992 \\
.65984 &amp; .34016
\end{bmatrix}
$
</center>

<p>So if today is sunny, we look at row 1 and can expect a 67.008% chance of sunny weather, and if it&#39;s rainy, row 2 shows a 65.984% chance for sunny weather. Nice! But you might be looking at that matrix and notice that row 1 and row 2 are <em>almost</em> the same. Watch what happens if we don&#39;t check for any 5 days in the future, but if we look towards an infinite number of days ahead?</p>
<center>
$
\lim\limits_{n\to\infty} M^n =
\begin{bmatrix}
.\overline{666} &amp; .\overline{333} \\
.\overline{666} &amp; .\overline{333}
\end{bmatrix}
$
</center>

<p>The rows <em>do</em> become the same. So, if we were to pick a random day far, far into the future, we can expect it to be twice as likely to be sunny than rainy regardless of today&#39;s weather. There&#39;s two important interpretations of this fact. 1) going back to our transformation of space idea, this <strong>equilibrium state</strong> is our eigenvector (specifically for $\lambda=1$) of our transition matrix $M$. Meaning, it is the solution to the matrix equation $vM = v$ where $v$ is a row vector (here, $v=\begin{bmatrix} .\overline{666} &amp; .\overline{333} \end{bmatrix}$). The second—and more important—way to think of this equilibrium state is that it is the final, or <strong>stationary</strong> distribution of sunny and rainy days. That is, if you took the fraction of $\frac{\textrm{Sunny Days}}{\textrm{Total Days}}$, you&#39;d expect it to approach $\frac{2}{3}$ as time went on, and $\frac{\textrm{Rainy Days}}{\textrm{Total Days}}$ to likewise approach $\frac{1}{3}$.</p>
<p>To summarize, here are a few important concepts about Markov chains:</p>
<ol>
<li>A Markov chain is a random process that describes the ability to switch between multiple states.</li>
<li>A Markov chain&#39;s probability for any future state depends only on the current state (this is also known as the <a href="https://en.wikipedia.org/wiki/Markov_property">Markov property</a>).</li>
<li>The sum of each row of a Markov chain&#39;s transition matrix must sum to 1 (something has to occur at each time step for each state, even if that means not changing states)</li>
<li>All Markov chains will eventually reach an equilibrium state that describes the final distribution of states over a long time.</li>
</ol>
<p>Markov chains are extremely powerful tools to model dynamics with multiple states due to their above properties, but some of their uses from chaos to disease modeling deserve their own post another day.</p>
<hr>
<p>If you understood this so far, you&#39;ve got the hardest part of Markov chain Monte Carlo methods under your belt. That being said, we are still missing second MC of MCMC.</p>
<h2 id="monte-carlo-simulations">Monte Carlo Simulations</h2>
<p><strong>Monte Carlo simulations</strong> are probably the closest you&#39;ll ever get to the scientific version of guess-and-check. The idea is if there is something that&#39;s too hard to calculate, you do a bunch of mini, random experiments to obtain data that can give us numerical approximations. It&#39;s very akin to Bayesian thinking: the more data you give to your approximation, the better the you can &quot;update&quot; your approximation to be more accurate and confident. As with all things, let&#39;s do a quick example.</p>
<p>If I hand you a coin, you probably would assume it&#39;s a fair coin: 50/50 chance for either heads or tails. But how could you verify that it is indeed a fair coin? Well you could flip it and see what it turns up as. Heads! &quot;It must be an unfair coin as it flips heads 100% of the time!&quot; said no one ever. Of course a single data point isn&#39;t nearly enough to draw any conclusions, so you need to flip it again. Heads again! Definitely weighted, right? Even if you get only heads twice in a row, that still isn&#39;t conclusive. You need to flip the coin a lot of times. By a lot, upwards of hundreds for a reasonable guess at the balance of the coin, and upwards of thousands for an ideal approximation. For all you know, those first 2 heads could be in a much larger sequence of flips you have yet to unfold:</p>
<center>
<code>H-H-T-H-T-T-H-T-T-T-H-T-H</code>
</center>

<p>Just like that, our coin reaches that 50/50 split significantly closer within just a few additional flips. </p>
<p>Each one of our data points were flips in this case, and we call those data points <strong>samples</strong>. The important part to note, though, is that there is a sense of randomness in each sample. The idea behind a Monte Carlo simulation is that even if our sampling method is random, the more samples we take will average out to the true value (think the <a href="https://en.wikipedia.org/wiki/Law_of_large_numbers]">Law of Large Numbers</a>). The is why the more samples we take, the more accurate our estimations become. This is a lot like unbiased sampling in research studies: you can&#39;t reasonably survey everyone in a population, so you take a smaller, random sample in the hopes that it will be representative <em>enough</em> to make reasonable conclusions of the larger population.</p>
<p>Again, just to summarize a few details:</p>
<ol>
<li>Monte Carlo simulations use random sampling to get numerical estimations for hard to otherwise calculate results.</li>
<li>The more samples/trials we take, the more accurate our results.</li>
<li>While taking more samples is more accurate, it also become less efficient to compute and gather results, so you have strike that balance between more accurate results or quicker results.</li>
</ol>
<hr>
<p>With all that out of the way, let&#39;s put it all together into one cool algorithm.</p>
<h2 id="metropolis-hastings-and-mcmc">Metropolis-Hastings and MCMC</h2>
<p>So far, we&#39;ve sampled from relativiely easy things to run trials on and get samples. Flipping a coin and rolling a dice are nice distributions to run trials on are they both can be modelled by a nice uniform distribution (even for weighted dice/coins by partitioning the uniformness). This is due to the niceness of a <strong>discrete</strong> distribution where there is only a finite number of results our black box can output. Often the case, we have a <strong>continuous function</strong> where we don&#39;t have probabilities for individual results, but rather a range of results. To get the gist of it, take the uniform probability distribution between $[0,1]$. What&#39;s the probability that you pick $0.235326…$? Obviously, out of an infinite amount of possibilities, a single, specific number to pick is probability 0. BUT, the probability of picking a number between $[.25,.75]$ is exactly $.5$, as we&#39;re picking from half of our total range. This is the idea of <strong>probability density</strong>. So, you can imagine for more complicated distributions (especially those taken from real life data) can be a lot more difficult to get samples from, or properly know the densities of regions. Here&#39;s where our MCMC comes from.</p>
<p><strong>Markov chain Monte Carlo</strong> methods combine two important aspects of the two concepts the name implies: a Markov chain&#39;s equilibrium distribution and Monte Carlo simulation&#39;s random sampling. Here, we make a Markov chain who&#39;s stationary distribution is <em>equal</em> to our hard-to-model probability distribution by doing a random walk around the distribution (for the sake of notation, we&#39;ll call our &quot;target&quot; distribution we&#39;re trying to model $\pi(x)$). In this case, we do so with the Metropolis-Hastings algorithm which is extremely simple:</p>
<ol>
<li>Pick a starting point $x_0 \rightarrow$ this is the start of our &quot;walk&quot;. An initial sample, if you will, that we provide ($x_t$ means our current sample at time $t$).</li>
<li>Now pick a new, <em>random</em> point $y$. Call $y$ the &quot;proposed state&quot; for $x_{t+1}$.</li>
<li><p>See how &quot;good&quot; $y$ is compared to $x_t$.</p>
<p>i. If $y$ is &quot;better&quot;, we let $x_{t+1}=y$</p>
<p>ii. If $y$ is &quot;worse&quot;, we <em>might</em> let $x_{t+1}=y$, but not always.</p>
</li>
<li>For $t=1,2,3,…$, repeat steps 2 and 3.</li>
<li>Profit.</li>
</ol>
<p>This is extremely vague, but I intentionally left it as such, because often times the formulas can confuse the language. In essence, this is what Metropolis-Hastings does to generate samples. We take a sample $x_t$ at a time $t$ that &quot;traces&quot; our distribution, and as $t$ gets larger, the more accurate our &quot;trace&quot; of the curve we walk around gets better. Let&#39;s put some of the formulas back into the instructions above and go at it one step at a time.</p>
<p><strong>Step 1</strong> is easy enough: we give any number for our algorithm to start with. Literally anything. You can give smart guesses that speed up the process, but that will be clear in a second.</p>
<p><strong>Step 2</strong> we don&#39;t actually perform, but rather design. Unlike Step 1 where we gave some determined number of our choosing, Step 2 we implement a <strong>transition kernel</strong> to pick a step for us. This kernel is a function $Q$ that takes a current spot $x$ and with some probability outputs a new spot $y$. That is, $Q$ is a distribution that randomly generates a new point $y$ <em>given</em> a current one $x$, which we will write $Q(y|x)$. This is how we make our &quot;proposed state&quot; and how we actually implement our walk. You may be wondering though, &quot;What <em>actually</em> is $Q$?&quot; Well, that&#39;s up to you to decide! Since $Q$ itself is a distribution around our current state $x$, you can shape $Q$ in whatever way you want! In general, though, it&#39;s not too important, but spending time to design a specific kernel can optimize and speed up the process.</p>
<p><strong>Step 3</strong> is our &quot;goodness&quot; check. Once we have a proposed state generated by $Q$, we need to see if this proposed state is in a more &quot;likely&quot; or dense spot on our distribution $\pi(x)$. The idea is we want to generate samples representative of $\pi(x)$, so it should be obvious that we should visit the probabilistically more dense spots, a.k.a. visit the spots the distribution says is more likely. Geometrically, this is a point <em>higher</em> on our distribution curve. </p>
<p><img src="/img/metropolis-hastings/metropolisAcceptance.png"></p>
<p>But remember, just because $y$ is not better doesn&#39;t mean that we outright reject it. We instead accept it with probability <em>proportional</em> to how much worse it is. If $y$ is half as high as our current spot $x$, we flip a coin and might accept it with 50% probability. If $y$ was a third as high $x$, we flip a weighted coin and might accept it with probability $\frac{1}{3}$. In other words, we can write our acceptance probability $A=\min(1, \frac{\pi(y)}{\pi(x)})$. If $y$ is higher than $x$, or $\pi(y)&gt;\pi(x)$, then $\frac{\pi(y)}{\pi(x)} &gt; 1$ and we accept it outright. If $\frac{\pi(y)}{\pi(x)} &lt; 1$, then we accept it with probability of that fraction. </p>
<p>This acceptance probability is also what makes this algorithm so good: we only need to know our target distribution $\pi(x)$ up to a constant! If $\pi(x) = c\cdot P(x)$, then our acceptance probability would be $A=\min(1, \frac{c\cdot P(y)}{c\cdot P(x)})$ which simplifies to $\min(1, \frac{P(y)}{P(x)})$, making the constant irrelevant. This is ideal for real life experiments as perfectly measuring constants from observation can be very difficult.</p>
<p><strong>Steps 4 and 5</strong> are pretty self-explanatory, so just to rewrite it more formally, here is the whole algorithm one more time:</p>
<ol>
<li>Pick a starting point $x_0$.</li>
<li>Sample a new proposal state $y$ with probability $Q(y|x_t)$</li>
<li><p>Compute $A=\min(1, \frac{\pi(y)}{\pi(x_t)})$.</p>
<p>i. With probability $A$, accept our proposed state and let $x_{t+1}=y$</p>
</li>
<li><p>For $t=1,2,3,…$, repeat steps 2 and 3.</p>
</li>
<li>Profit.</li>
</ol>
<p>However I must admit, I did lie to you, but only a <em>little</em> bit. The acceptance probability I gave is actually for the Metropolis algorithm, not the Metropolis-Hastings algorithm. The acceptance probability for the Metropolis-Hastings algorithm is $A=\min(1, \frac{\pi(y)Q(x_t|y)}{\pi(x)Q(y|x_t)})$. This is because the Metropolis algorithm only works when $Q$ is a symmetric distribution, meaning that $Q(y|x_t)=Q(x_t|y)$, which returns us to our familiar fraction from before. MH allows asymmetric kernels to speed up the algorithm, but otherwise the concept is the same.</p>
<p>With 5 very simple steps, we are able to take samples from continuous distributions just like that! The Monte Carlo aspect is pretty obvious with the random steps with generating random &quot;proposal states&quot; $y$ in <strong>Step 2</strong>. The Markov chain might be a bit more concealed, as we never actually explicitly define it. But, look at <strong>Step 3</strong> again, as that resembles something very close to our transition probabilities before. Step 3 is actually our Markov chain <em>implicitly</em> defined! Since there are an infinite number of states/values to pick and another infinite number of states to transition to, we can&#39;t define an infinitely sized transition matrix. So, instead, we define transition probabilities as needed with our kernel $Q$. And notice, our kernel maintains the Markov property as each proposed state only relies on the current. This is because we sort of reversed the way we defined our Markov chain! In our weather example with sunny and rainy days from above, we defined transition states and the stationary distribution followed suit, almost like property or characteristic of our Markov chain. Here, our Markov chain is instead defined by the fact we want our stationary distribution to mimic $\pi(x)$. This is why we don&#39;t outright reject states that are less &quot;good&quot; in our acceptance probability, but rather accept it proportional to how less &quot;good&quot; it is as that will reflect our distribution&#39;s shape.</p>
<p>But just like in our original Markov chain example, it&#39;s not perfect immediately. Notice in our original weather example with sunny and rainy days, 2 iterations with $M^2$ was no where near close our stationary distribution, and while 5 iterations at $M^5$ was closer, it still was nowhere near ideal. You have to <em>burn in</em> some states before proper, accurate samples can be generated. </p>
<p>Here&#39;s some short Python to implement the Metropolis-Hastings algorithm to estimate the following Laplace distribution:</p>
<center>
$\large{\pi(x)=\frac{1}{2}\exp(-|x|)}$
</center>

<p>Here it is in only 20 lines of code:</p>
<p><!-- HTML generated using hilite.me --><div style="background: #272822; overflow:auto;width:auto;border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em; font-size: 11pt;"><pre style="margin: 0; line-height: 125%"><span style="color: #f92672">import</span> <span style="color: #f8f8f2">numpy</span> <span style="color: #66d9ef">as</span> <span style="color: #f8f8f2">np</span>
<span style="color: #f92672">import</span> <span style="color: #f8f8f2">matplotlib.pyplot</span> <span style="color: #66d9ef">as</span> <span style="color: #f8f8f2">plt</span></p>
<p><span style="color: #66d9ef">def</span> <span style="color: #a6e22e">target</span><span style="color: #f8f8f2">(x):</span>
  <span style="color: #66d9ef">return</span> <span style="color: #f92672">.</span><span style="color: #ae81ff">5</span> <span style="color: #f92672">*</span> <span style="color: #f8f8f2">np</span><span style="color: #f92672">.</span><span style="color: #f8f8f2">exp(</span><span style="color: #f92672">-</span><span style="color: #f8f8f2">abs(x))</span> <span style="color: #75715e"># Target distribution π(x)</span></p>
<p><span style="color: #66d9ef">def</span> <span style="color: #a6e22e">accept</span><span style="color: #f8f8f2">(p):</span>
  <span style="color: #f8f8f2">flip</span> <span style="color: #f92672">=</span> <span style="color: #f8f8f2">np</span><span style="color: #f92672">.</span><span style="color: #f8f8f2">random</span><span style="color: #f92672">.</span><span style="color: #f8f8f2">uniform(</span><span style="color: #ae81ff">0</span><span style="color: #f8f8f2">,</span><span style="color: #ae81ff">1</span><span style="color: #f8f8f2">)</span>
  <span style="color: #66d9ef">return</span> <span style="color: #f8f8f2">p</span> <span style="color: #f92672">&gt;=</span> <span style="color: #f8f8f2">flip</span></p>
<p><span style="color: #66d9ef">def</span> <span style="color: #a6e22e">metropolis</span><span style="color: #f8f8f2">(iterations):</span>
  <span style="color: #f8f8f2">states</span> <span style="color: #f92672">=</span> <span style="color: #f8f8f2">[]</span> <span style="color: #75715e"># Samples generated by the algorithm</span>
  <span style="color: #75715e"># Step 1 --&gt; initialize an x0</span>
  <span style="color: #f8f8f2">current</span> <span style="color: #f92672">=</span> <span style="color: #ae81ff">1</span> 
  <span style="color: #66d9ef">for</span> <span style="color: #f8f8f2">i</span> <span style="color: #f92672">in</span> <span style="color: #f8f8f2">range(iterations):</span>
    <span style="color: #f8f8f2">states</span><span style="color: #f92672">.</span><span style="color: #f8f8f2">append(current)</span>
    <span style="color: #75715e"># Step 2 --&gt; Q generates a proposal (normal distribution)</span>
    <span style="color: #f8f8f2">proposal</span> <span style="color: #f92672">=</span> <span style="color: #f8f8f2">np</span><span style="color: #f92672">.</span><span style="color: #f8f8f2">random</span><span style="color: #f92672">.</span><span style="color: #f8f8f2">normal(current,</span> <span style="color: #ae81ff">1</span><span style="color: #f8f8f2">)</span> 
    <span style="color: #75715e"># Step 3 --&gt; Check how good our proposal is</span>
    <span style="color: #f8f8f2">goodness</span> <span style="color: #f92672">=</span> <span style="color: #f8f8f2">min(</span><span style="color: #ae81ff">1</span><span style="color: #f8f8f2">,</span> <span style="color: #f8f8f2">target(proposal)</span><span style="color: #f92672">/</span><span style="color: #f8f8f2">target(current))</span>
    <span style="color: #66d9ef">if</span> <span style="color: #f8f8f2">accept(goodness):</span> 
      <span style="color: #f8f8f2">current</span> <span style="color: #f92672">=</span> <span style="color: #f8f8f2">proposal</span> <span style="color: #75715e"># If we like the proposal state, we jump there!</span>
  <span style="color: #66d9ef">return</span> <span style="color: #f8f8f2">states</span>
</pre></div></p>
<p>Here is the scatter plot of our algorithm walking all around $\pi(x)$ across 10000 iterations...</p>
<p><img src="/img/metropolis-hastings/scatterMH.png"></p>
<p>...and here is the corresponding histogram that fits almost too perfectly to our target distribution.</p>
<p><img src="/img/metropolis-hastings/histogramMH.png"></p>
<p>We can now generate discrete samples proportional to our continuous distribution!</p>
<hr>
<p>The algorithm aside, an extremely important concept is shown here: reframing questions and objects and asking them from a different perspective can lead to extremely powerful tools and thoughts. We take a Markov chain, and instead of letting its equilibrium state arise as a property, we use it to turn our definition inside out and use the equilibrium state itself to define the Markov chain. This pattern of rethinking concepts has always been a useful, sobeit from building intuition while learning, to defining tools in all of math. From connecting why Mandelbrot set to its cardioid and cycloids, to encoding parameters in 4-dimensional space means, to even Fourier rebuilding <a href="https://en.wikipedia.org/wiki/Fourier_series">functions from sine waves</a>, the most impactful question one can ask is usually in the form of, &quot;What if?&quot;</p>
]]></description>
         <link>http://xperimex.github.io/blog/metropolis-hastings</link>
         <guid isPermaLink="true">http://xperimex.github.io/blog/metropolis-hastings</guid>
         <dc:creator><![CDATA[Adi Mittal]]></dc:creator>
      </item>
      <item>
         <title><![CDATA[Fruitful Fractions and Delightful Dice]]></title>
         <description><![CDATA[A powerful tool to reimagine counting 

 <script src="https://www.desmos.com/api/v1.4/calculator.js?apiKey=dcb31709b452b1cf9dc26972add0fda6"></script>

<p>Try typing the fraction $\frac{1}{98}$ into your calculator see what you get. Don&#39;t have one on hand? Here&#39;s a calculator ready and waiting for you.</p>
<center>
  <div id="calculator" style="width: 610px; height: 375px;"></div>
  <script src="/js/scientificFraction.js"></script>
</center>


<p>Next try $\frac{100}{9899}$. See if anything stands out to you. Even with the few amount of decimals this displays, you might notice some patterns appearing. $\frac{1}{98}$ expanded as a decimal appears to contain the powers of 2! The second fraction might require for a more robust calculator, but with enough decimals it&#39;s clear that it too has a hidden sequence: the Fibonacci numbers are in its decimal expansion!</p>
<p>You can try and guess at other fractions with unique expansions, but there is a systematic way to generate these fractions to show not just simple sequences like this, but any sequence you want! It&#39;s all a byproduct of one of the most powerful tools in discrete math and combinatorics: the generating function.</p>
<h2 id="generating-functions-and-recurrence-relations">Generating Functions and Recurrence Relations</h2>
<p>First, some terminology and context. A <strong>generating function</strong> may look complicated, but its essence is actually very simple. If you have some sequence of numbers, say, $A = \{ a_0, a_1, a_2, a_3, \cdots \}$, its corresponding generating function is the power series $A(x) = a_0 + a_1x^1 + a_2x^2 + a_3x^3 + \cdots$. That&#39;s all a generating function is! If you like fancy math notation, we can write this more concisely as $A(x) = \sum_{n=0}^{\infty} a_nx^n$. Something important to note, though, is that the powers of $x$ in the series don&#39;t actually <em>mean</em> anything. We only really care about the coefficients, and we happen to be using the series to <strong>encode</strong> our sequence $A$. Herbet S. Wilf put this best in his aptly named book, <a href="https://www2.math.upenn.edu/~wilf/gfology2.pdf">generatingfunctionology</a>: &quot;A generating function is a clothesline on which we hang up a sequence of numbers for display.&quot; Basically, our generating function is purely a convenient way to place all of our sequence terms into a singular object. That&#39;s why it&#39;s not just any power series, but a <em>formal power series</em>, where it extends on towards an infinite number of terms where we don&#39;t really care about convergence, but rather just the representation itself. What&#39;s great about generating functions too are that it turns questions about sequences and integers into one about functions, and over the course of centuries, we can do a <em>lot</em> with functions. You&#39;ll see quickly why we use a power series specifically, as exponent properties play very nicely into the types of problems and tricks generating functions can help us out with. Knowing this, you shouldn&#39;t let the notation of a generating function ever scare you! They&#39;re truly a simple object obscured by harsh notation, so always focus what they represent instead of how they are written.</p>
<p>So, for our powers of 2, its sequence would be $P=\{ 2^n \}_{n=0}^{\infty}$ and corresponding generating function would be $P(x) = 1+2x+4x^2+8x^3+\cdots$. If you&#39;re familiar with your series, this is a geometric series and we can condense it into the following formula: $A(x) = 1+(2x)^1+(2x)^2+(2x)^3 + \cdots = \frac{1}{1-2x}$. Remember how I said the powers of $x$ don&#39;t really mean anything? This is a case where we can actually leverage the fact that our generating function is in fact a &quot;function&quot; (this is a specific use case as we normally don&#39;t treat them as standard functions). Consider the general generating function $A(x)=a_0+a_1x+a_2x^2+a_3x^3+\cdots$. Watch what happens if we plug in $A(.1) = a_0+a_1(.1)+a_2(.001)+a_3(.0001)+\cdots$. This may not look like much, but since we use a base 10 counting system, plugging in $.1$ is the same thing as moving a decimal point to the left one spot. So, we can rewrite that infinite sum as the nice float $a_0.a_1a_2a_3\ldots$ Each number in our sequence becomes a decimal in our final number! </p>
<p>But, this can become a problem if a number in our sequence $a_n$ is more than one digit long, so we can change the value we plug in to get more precise decimals with more numbers from our sequence: $A(.01) = a_0.0a_10a_20a_3\ldots$ and just like that we have buffer 0s in between numbers. So, doing this for our generating function for the powers of 2, we get that $P(.01) = \frac{1}{1-2(.01)} = \frac{1}{.98} = 1.0204081632\ldots$ Just for aesthetic pleasure, I like to multiply the final fraction by the value of $x$ we plugged in to shift that initial $a_0$ after the decimal point, and get a nicer looking fraction at the end: $\frac{1}{.98}\cdot .01 = \frac{1}{98}$, giving the familiar fraction from the start and the nice decimal of $.010204081632\ldots$</p>
<p>As cool as this may be, this relied on the fact we recognized what kind of series the generating function was (for the powers of 2, it was geometric). Let&#39;s take a look at a slightly more complicated sequence: the Fibonacci sequence. Unlike the powers of 2 where we knew a nice closed formula off the bat for each term, we don&#39;t have one (shhh) for the Fibonacci numbers. Instead, we can define the sequence by relating it to other terms. We&#39;ll call the Fibonacci sequence $F = \{ f_0, f_1, f_2, f_3, \cdots \}$ and its associated generating function $F(x) = \sum_{n=0}^{\infty} f_nx^n$ where $f_n$ is the nth Fibonacci number. By definition of the Fibonacci numbers, we also know that</p>
<center>
$f_{n+2} = f_{n+1} + f_n \hspace{.3cm} (f_0 = 0, f_1 = 1)$
</center>

<p>This equation is known as a <strong>recurrence relation</strong>, as, well, it&#39;s a recursive relationship; any given term in the sequence can be expressed in some form related to other terms. What&#39;s useful about having an equation like this is that we can relate this to our generating function! If we can solve for the generating function, we might be able to get a function that can get us our cool fraction with the sequence embedded in the decimals again! If we multiply through by $x^n$, we get…</p>
<center>
$f_{n+2}x^n = f_{n+1}x^n + f_nx^n$
</center>

<p>…and then we sum over from $0$ to $\infty$ we end up with…</p>
<center>
$\sum_{n=0}^{\infty} f_{n+2}x^n = \sum_{n=0}^{\infty} f_{n+1}x^n + \sum_{n=0}^{\infty} f_nx^n$
</center>

<p>We&#39;re now starting to have a set of terms that awfully resemble our generating function $F(x)$. Let&#39;s look at the left-hand and see if we can make any sense of it. Just writing it out can tell us a lot, so let&#39;s do that.</p>
<center>
$\sum_{n=0}^{\infty} f_{n+2}x^n = f_2 + f_3x + f_4x^2 + f_5x^3 + \cdots$
</center>

<p>It looks like our original generating function, but offset! Remember, we want the subscript of the term coefficient to equal the power of the $x$ it is attached to. We can multiply through by $x^2$ to easily fix that.</p>
<center>
$x^2 \cdot \sum_{n=0}^{\infty} f_{n+2}x^{n} = f_2x^2 + f_3x^3 + f_4x^4 + f_5x^5 + \cdots$
</center>

<p>However, we don&#39;t want to actually change the value of our recurrence and add extra factors to both sides. To counter the effects of the multiplication, we just add a term of $\frac{1}{x^2}$ before it since $\frac{1}{x^2} \cdot x^2 = 1$, negating the effects of our multiplication.</p>
<center>
$\sum_{n=0}^{\infty} f_{n+2}x^{n} = \frac{1}{x^2}(f_2x^2 + f_3x^3 + f_4x^4 + f_5x^5 + \cdots)$
</center>

<p>Now look at that right-hand side: it&#39;s our generating function $F(x)$ missing the first two terms, $f_0$ and $f_1x$!</p>
<center>
$F(x) = \color{red}{f_0 + f_1x} + f_2x^2 + f_3x^3 + f_4x^4 + f_5x^5 + \cdots$
<br>
$F(x) \color{red}{- f_0 - f_1x} = f_2x^2 + f_3x^3 + f_4x^4 + f_5x^5 + \cdots$
</center>

<p>Finally, after plugging it all back in, we end up with</p>
<center>
$\sum_{n=0}^{\infty} f_{n+2}x^{n} = \frac{1}{x^2}(F(x)-f_0-f_1x)$
</center>

<p>You can do a similar process with the other terms on the right-hand side of our original equation to finally get an expression in terms of the generating function, instead of the recurrences.</p>
<center>
$\frac{1}{x^2}(F(x)-f_0-f_1x) = \frac{1}{x}(F(x)-f_0) + F(x)$
</center>

<p>Now we just need to turn the wheel and solve for $F(x)$!</p>
<center>
$\begin{align}
\frac{1}{x^2}(F(x)-f_0-f_1x) &amp; = \frac{1}{x}(F(x)-f_0) + F(x) \
\newline
F(x)-f_0-f_1x &amp; = F(x)x-f_0x + F(x)x^2 \
\newline
F(x)-F(x)x-F(x)x^2 &amp; = f_0 - f_0x + f_1x \
\newline
F(x)(1-x-x^2) &amp; = f_0 - f_0x + f_1x \
\newline
F(x) &amp; = \small{\frac{f_0 - f_0x + f_1x}{1-x-x^2}} \
\end{align}$
</center>

<p>Remember, we had initial values $f_0=0$ and $f_1=1$, so we can plug those in to further simplify our fraction.</p>
<center>
$F(x) = \large{\frac{x}{1-x-x^2}}$
</center>

<p>And sure enough, $F(.01) = \frac{100}{9899} = 0.0101020305081321 \ldots$</p>
<p>But why stop there? Although we just solved that $F(x) = \frac{x}{1-x-x^2}$, don&#39;t forget our original definition that $F(x) = \sum_{n=0}^{\infty}f_nx^n$. These equations imply that if we can find a power series $\sum_{n=0}^{\infty}f_nx^n = \frac{x}{1-x-x^2}$, we should get a closed form for the nth Fibonacci number!</p>
<p>First, we need to decompose our function into its <a href="https://brilliant.org/wiki/partial-fractions/">partial fractions</a>. Let $\phi = \frac{1+\sqrt{5}}{2}$ and $\varphi = \frac{1-\sqrt{5}}{2}$.</p>
<center>
$\normalsize{ \frac{x}{1-x-x^2} = \frac{x}{(1-\phi x)(1-\varphi x)} = \frac{1}{\phi-\varphi}(\frac{1}{1-\phi x} - \frac{1}{1-\varphi x}) = \frac{1}{\sqrt{5}}(\frac{1}{1-\phi x} - \frac{1}{1-\varphi x}) }$
</center>

<p>Note our final result mimics the closed form of two different geometric series!</p>
<center>
$\frac{1}{\sqrt{5}}(\frac{1}{1-\phi x} - \frac{1}{1-\varphi x}) = \frac{1}{\sqrt{5}} ( \sum_{n=0}^{\infty}(\phi x)^n - \sum_{n=0}^{\infty}(\varphi x)^n) = \sum_{n=0}^{\infty}\frac{\phi^n-\varphi^n}{\sqrt{5}}x^n$
</center>

<p>So, to wrap it all up:</p>
<center>
$F(x) = \sum_{n=0}^{\infty}f_nx^n = \sum_{n=0}^{\infty}\frac{\phi^n-\varphi^n}{\sqrt{5}}x^n \rightarrow$ 
<br><br>
$\large{f_n = \frac{\phi^n-\varphi^n}{\sqrt{5}}}$
</center>

<p>Just like that, we&#39;ve found a formula for the nth Fibonacci number (this is known as <a href="https://artofproblemsolving.com/wiki/index.php/Binet%27s_Formula">Binet&#39;s formula</a>)! This is only a <em>sliver</em> of the power of generating functions: being able to turn a recurrence relation into a closed form solution, barely even interacting with the sequence at all! </p>
<p>Now, let&#39;s try a different type of problem generating functions can help us out with.</p>
<h2 id="counting-birds-with-generating-functions">Counting Birds with Generating Functions</h2>
<p>Say you&#39;re visiting an aviary with some friends. Well-respected, the aviary has a vast number of birds, but they&#39;ve noticed some interesting patterns in the behavior of their avifauna: their hummingbirds always fly solo; blue jays tend to nest in fours; toucans perch in pairs; and cassowaries chill in fives. How many ways can you see a total of 20 birds? </p>
<p>This may seeem like an odd spot for generating functions, but we&#39;ll see a nice property of exponents that allows us to use them. Here, a generating function $A(x) = \sum_{n=0}^{\infty}a_nx^n$ is an encoding such that each term $a_n$ denotes how many ways there are to see $n$ birds. Let&#39;s write the generating function for hummingbirds:</p>
<center>
$H(x) = 1+x+x^2+x^3+x^4+\cdots$
</center>

<p>So, if we want to see any number of birds, there is exactly one way we can see that many birds with only seeing hummingbirds. That makes sense! What about blue jays?</p>
<center>
$B(x) = 1+x^3+x^6+x^9+x^{12}+\cdots$
</center>

<p>Jays come in groups of 3, so it would make sense we could only see total birds in multiples of 3. If we want to see a group of 6 birds with only jays, there is one way we can do that (that is by seeing two groups of jays), but 0 ways to see 5 birds of only jays. Similar generating functions can be written for the other birds.</p>
<center>
$\begin{align}
H(x) &amp; = 1+x+x^2+x^3+x^4+\cdots
\newline
B(x) &amp; = 1+x^3+x^6+x^9+x^{12}+\cdots
\newline
T(x) &amp; = 1+x^2+x^4+x^6+x^8+\cdots
\newline
C(x) &amp; = 1+x^5+x^{10}+x^{15}+x^{20}+\cdots
\end{align}$
</center>

<p>The surprising thing is now, if we want to see the number of ways to see $n$ birds through a combination of different birds, all we have to do is multiply the generating functions together! But why would this ever work? Well, let&#39;s think of what our exponents mean in each function: they are the total number of birds we see from a group. So, if our giant product results in a term of, say, $x^{14}$, we know that is one way to see 14 birds. Why? Because exponents turn multiplication into addition: $x^a \cdot x^b = x^{a+b}$. So, if we get multiple copies of $x^{14}$, they&#39;ll all accumulate in the coefficient of that term, giving us the different ways to see a total of 14 birds! This is why using a power series specifically for generating functions are so helpful: not only do the exponents have a clear meaning when applied, they also carry over the nice exponent properties we can leverage in counting. In general, to count the number of ways to see $n$ birds, we look for the coefficient in front of $x^n$.</p>
<center>
$H(x)B(x)T(x)C(x) = $
<br> 
$(1+x+x^2+\cdots)(1+x^3+x^6+\cdots)(1+x^2+x^4+\cdots)(1+x^5+x^{10}+\cdots)$
</center>

<p>Expanding that out seems like a terrible idea, so we won&#39;t… We&#39;ll let Python do it instead! It&#39;s totally doable to do this by hand to systematically <em>extract the coefficient</em> of $x^{20}$ (especially with the series we&#39;ve selected, involving many binomial coefficients with its partial fraction decomposition), but the algebra along with it can get annoyingly tedious. I&#39;m sure there are clever ways to go about keeping track of which terms you&#39;re multiplying, but that&#39;s out of the scope of this post. </p>
<center>
$H(x)B(x)T(x)C(x) = 1+1x+2x^2+3x^3+ \cdots + 80x^{19} + 91x^{20} + 101x^{21}+\cdots$
</center>

<p>So, if you go to the aviary, we know there are 91 different ways to see a total of 20 birds. If you&#39;re interested in seeing the entire mathematical crank turn, great YouTuber Mathologer made an excellent video answering a similar question <a href="https://www.youtube.com/watch?v=VLbePGBOVeg">counting the number of ways to make change for dollar</a> in which he spends much more time going into detail the algebra to solve such a problem analytically. Regardless, I hoped this gave insight into how great generating functions are as a combinatorial tool for counting, in addition to its utility as a discrete tool.</p>
<p>Before we end, I want to show you one more cool use case of generating functions that involve probability distributions.</p>
<h2 id="delightful-dice-and-probability-distributions">Delightful Dice and Probability Distributions</h2>
<p>A staple of tabletop gaming has always been the pair of six-sided dice. Notably, it&#39;s respected for being a considerably fair distribution, with the most likely outcome being the middle value of 7 at $\frac{1}{6}$, and the two extreme values of 2 and 12 being the least likely, both at probability $\frac{1}{36}$. This makes it great for board games, with extraordinarily good, high values being just as likely as their low, unlucky counterparts. But, these dice are boring: for centuries our dice have remained a simple numbering from 1–6, but is there a different numbering that we can use to maintain our fair play?</p>
<p>If we use our familiar friend the generating function, we can find out with little thinking required! We can represent our die as a generating function $P(x) = \sum_{n=0}^{\infty}p_nx^n$ where $p_n$ is the probability of rolling a value $n$. So, for a standard die its generating function would be</p>
<center>
$\normalsize{\frac{1}{6}x^1+\frac{1}{6}x^2+\frac{1}{6}x^3+\frac{1}{6}x^4+\frac{1}{6}x^5+\frac{1}{6}x^6}$
</center>

<p>as you have an equal chance of rolling any number 1–6, and no other possible number (so all of their coefficients are 0 and get cancelled out). If we had a die with sides 1,2,2,7,7,7, it&#39;s generating function would look like</p>
<center>
$\normalsize{\frac{1}{6}x^1+\frac{1}{3}x^2+\frac{1}{2}x^7}$
</center>

<p>So, the generating function of the sum of <em>two</em> dice are just it&#39;s product like last time (to see why this is true, think about what the product means: exponents multiply into a sum, and therefore count the number of ways to sum a number from rolling two dice. We then normalize it by $\frac{1}{36}$ to get final probabilities). So, if we had two new dice—we&#39;ll call them die A and die B—with new generating functions $A(x)$ and $B(x)$, their product should equal the product of the normal dice!</p>
<center>
$A(x)B(x) = \frac{1}{36}(x^1+x^2+x^3+x^4+x^5+x^6)^2$
</center>

<p>So, now what? The right-hand side is currently packaged as two factors: two copies of the normal die&#39;s generating function. That means that if we can find a way to re-factor that right-hand side into two new generating functions, we should get the labelling for two new dice that are still just as fair as our ordinary dice!</p>
<center>
$\begin{align}
  \frac{1}{36}(x^1+x^2+x^3+x^4+x^5+x^6)^2 &amp; = \frac{1}{36}x^2(1+x+x^2+x^3+x^4+x^5)^2 \
  \newline
  &amp; = \frac{1}{36}x^2(1+x+x^2)^2(1+x^3)^2
  \newline
  &amp; = \frac{1}{36}x^2(1+x+x^2)^2(1+x)^2(1-x+x^2)^2
\end{align}$
</center>

<p>Now, we just need to figure out how to repackage this into 2 terms and we should have our dice! Some things to note: 1) All the coefficients in $A(x)$ and $B(x)$ need to be nonnegative multiples of $\frac{1}{6}$, as they all should have positive probabilitiy of rolling something and each die has 6 sides. 2) A(x) and B(x) both need to have at least one factor of $x$ as if otherwise, we might end up with 0s on our dice (which can make for some very boring dice). So, right now we have $A(x) = \frac{1}{6}x$ and $B(x) = \frac{1}{6}x$. Now we need to distribute the remaining factors $(1+x+x^2)^2(1+x)^2(1-x+x^2)^2$. Since we only have six sides on our dice, it follows that our coefficients of both $A(x)$ and $B(x)$ must sum to 6 (how can we put 7 numbers on a six sided die?). Since our factors&#39; have coefficient sums of 3, 2, and 1 respectively, <a href="#footnote">it follows immediately that both $A(x)$ and $B(x)$ need at least one factor of $(1+x+x^2)$ and one factor of $(1+x)$</a>. So, what do we do with the two factors of $(1-x+x^2)^2$? We can either give both to die A (or B, whichever you like thanks to symmetry), or one to A and one to B. If we do the latter, we get:</p>
<center>
$\begin{align}
A(x) &amp; = \frac{1}{6}x(1+x+x^2)(1+x)(1-x+x^2) \
\newline
&amp; = \frac{1}{6}(x^1+x^2+x^3+x^4+x^5+x^6) \
\newline
B(x) &amp; = \frac{1}{6}x(1+x+x^2)(1+x)(1-x+x^2) \
\newline
&amp; = \frac{1}{6}(x^1+x^2+x^3+x^4+x^5+x^6)
\end{align}$
</center>

<p>Which is just our normal dice from before, labelling both dice 1,2,3,4,5,6. But if we try the former option...</p>
<center>
$\begin{align}
A(x) &amp; = \frac{1}{6}x(1+x+x^2)(1+x)(1-x+x^2)^2 \
\newline
&amp; = \frac{1}{6}(x+x^3+x^4+x^5+x^6+x^8) \
\newline
B(x) &amp; = \frac{1}{6}x(1+x+x^2)(1+x) \
\newline
&amp; = \frac{1}{6}(x+2x^2+2x^3+x^4)
\end{align}$
</center>

<p>Now we get two very unique dice: label die A 1,3,4,5,6,8 and die B 1,2,2,3,3,4. Of course, multiplying these two generating functions together will verify their fairness as we didn&#39;t actually change any of the factors that goes into it, but you can also draw these dice&#39;s summation table and verify that all the numbers 2–12 appear as much as they should. If you want to mess with your friends a bit, making a pair of these dice for your next occasion is definitely an easy project to do in a day.</p>
<h2 id="conclusion">Conclusion</h2>
<p>Hopefully this has shown you just how powerful generating functions and how wide of an application they have in discrete problems. From sequences, to counting, to probability, these are just a fraction of the potential generating functions have, and should always be kept in the back of your mind as not just a tool, but really as a symbol of an ongoing theme in problem solving: always look for out-of-the-box perspectives. I&#39;ve spoken about duality a bit before (and it definitely warrants its own post), but just how powerful alternative representations can be can&#39;t be understated. Generating functions took seemingly impossible questions about discrete sequences and indistinguishable counting to questions about functions and series and required at most a bit of high school algebra to manipulate some of the equations.</p>
<h3 id="footnote">Footnote</h3>
<p>While I left links to resources for relevant techniques and tools that I didn&#39;t explain, I do want to talk briefly on how I determined distributing factors for our polynomial coefficients in the dice problem as it&#39;s not completely obvious if you haven&#39;t seen it before. In the dice problem, I said that we need our final polynomial&#39;s coefficients to sum to 6. To ensure they summed to 6, I said that they both must be the product of a polynomial with coefficient sum of 3 and a polynomial with a coefficient sum of 2. This is because of the nice property that the product of two polynomials&#39; coefficient sum is equal to the coefficient sum of their polynomial product. In other words: let $C$ be a function that takes a polynomial $f(x)$ as an argument, $C(f(x))$ returns the sum of the coefficients of $f(x)$. I want to show you that $C(f(x)) \cdot C(g(x)) = C(f(x)g(x))$. </p>
<p>Let&#39;s first do an example. Let $f(x) = x^2 - 3x + 2$ and $g(x) = 2x - 4$. The coefficient sum of $f(x)$ is $C(f(x)) = 1-3+2 = 0$. Similarly, for $C(g(x)) = 2-4 = -2$. Therefore, $C(f(x))\cdot C(g(x)) = 0\cdot -2 = 0$. So, we&#39;d then expect $C(f(x)g(x)) = 0$ as well.</p>
<p>Now, let&#39;s see what the product of the two functions is and what its coefficient sum is. Let $h(x) = f(x)g(x) = 2x^3 - 10x^2 + 16x - 8$. Then, $C(h(x)) = 2-10+16-8 = 0$, just as we foresaw.</p>
<p>Why is this true? It comes down to a clever way of viewing the coefficient sums. Note that for any polynomial $f(x)$, $C(f(x)) = f(1)$. This fact is because plugging in 1 to any polynomial completely removes the powers of $x$, as $1^n = 1$ and $m\cdot 1 = m$, leaving us only with the coefficients. This allows us to rewrite $C(f(x)) \cdot C(g(x)) = f(1)\cdot g(1)$. Now, what about $C(f(x)g(x))$? Well, remember we defined $h(x) = f(x)g(x)$, so that means $C(f(x)g(x)) = C(h(x)) = h(1) = f(1)\cdot g(1)$, which is exactly what we got before! So this means that for any polynomial with coefficient $n$, it can be written as the product of two smaller polynomials with coefficient sums $a$ and $b$ with the only requirement that $ab = n$. That&#39;s how I knew in the dice problem that each die&#39;s generating function needed a factor with coefficient sums 3 and 2, since $3\cdot 2 = 6$.</p>
]]></description>
         <link>http://xperimex.github.io/blog/generating-functions</link>
         <guid isPermaLink="true">http://xperimex.github.io/blog/generating-functions</guid>
         <dc:creator><![CDATA[Adi Mittal]]></dc:creator>
      </item>
      <item>
         <title><![CDATA[Steiner's Porism and Incredible Inversions]]></title>
         <description><![CDATA[Time to flip circles inside out 

 <script src='https://cdnjs.cloudflare.com/ajax/libs/g9/1.0.16/g9.js'></script>
<script src="https://unpkg.com/mathjs/lib/browser/math.js"></script>

<!-- <img src="/img/steiners-porism/steinersAnimated.gif"> -->
<div id="hook" style="flex: 2; position: relative;"></div>

<p>Today I want to talk about a type of geometry I think is grossly overlooked, especially when compared to the popularity of its Euclidean brother. In a world where linear transformations are the norm between translations, rotations, and dilations, sometimes it&#39;s hard to see anything but them as the workhorse geometric tools. However, there is an additional transformation that takes us from the solidarity of linear transforms to one of a type of circular transform that may seem novel at first, but is able to even extend complex analysis. Today I want to talk about <strong>inversive geometry</strong>. Inversive geometry takes the standard plane we know and quite literally flips it inside out. By the end of this post, you will be familiar with not only what in the world an inversion is, but a very cool theorem that results in the animation above that relates tangent circles to one another. But before we can get there, we first need to learn <em>how</em> to flip our world inside out.</p>
<h2 id="plane-inversions">Plane Inversions</h2>
<p>As you can imagine, inversive geometry is geometry that relies on something called <em>inversions</em>. You can think of an inversion as a function that takes a point $P$ and spits out a transformed point $P&#39;$. But, what exactly is our function? It&#39;s not a standard $f(x)$ as we&#39;re giving <em>two</em> coordinates not one. So maybe it&#39;s a 2-by-2 matrix, as we&#39;re giving a 2D vector and outputting another 2D vector? Not a bad idea, but it will quickly become clear why we don&#39;t want to do that. So, what <i>is</i> our functional object? It&#39;s actually a <em>circle</em>. As weird as that sounds, just hear it out. Given a circle $Ø$ with center $O$ and radius $r$, the point $P$ is inverted to $P&#39;$ based on the following equation: </p>
<center>
$\large{|OP| \cdot |OP&#39;| = r^2}$ 
</center>

<p>...where $P&#39;$ lies on the ray $\overrightarrow{OP}$. Try dragging the points below to get a handle on this idea.</p>
<div id="inversionIntro" style="flex: 2; position: relative;"></div>

<center style="color: #666;">
<p>Here we have the green circle $Ø$ which we are inverting the point $P$ over. Try dragging $P$, $O$, and $R$ around to see where its image $P&#39;$ goes under inversion.</p>
</center>

<p>The numbers above each point represent their distance from $O$, so you can verify the distances satisfy the inversion equation. As a nice little double entendre, this mapping is called an inversion for both algebraic and geometric reasons. The equation itself is an inverse relationship between $|OP|$ and $|OP&#39;|$ (this is why we can&#39;t use matrices <a href="https://math.stackexchange.com/questions/2626356/ill-known-original-interesting-investigations-on-applications-of-inversion-the?rq=1">in the standard sense to represent the transform</a>), but better yet, I&#39;m sure within just within a few seconds that you can much more intuitively see the geometric reason: every point $P$ on the inside of the circle gets mapped to the outside of the circle, and every point outside the circle gets mapped to the inside (and every point <i>on</i> the circle stays on the circle—we say the circle itself is <em>invariant</em> under inversion). We&#39;re taking our plane and flipping it inside out centered around the circle. </p>
<p>As such, this specific inversion is known as a <strong>circle inversion</strong> or <strong>plane inversion</strong>.</p>
<p>However, there might be a glaring issue to some of you: what if the point $P$ we&#39;re inverting is the center of the circle $O$ itself? Then we get $|OP|=0$, and how can 0 times anything equal anything but 0? To get around this issue, we have to formally introduce a <em>point at infinity</em>. That way, if we try to invert the center of our inverting circle, we have a place for it to go. </p>
<h2 id="circles-inverting-circles">Circles Inverting Circles</h2>
<p>Now that we can invert points, we can now easily invert <em>shapes</em>. All we have to do is invert the collection of points individually, and remember the order to connect them. We could try basic polygons like squares and triangles, but the one that is most interesting (and will be most helpful) is inverting other circles. Below, we&#39;ll again invert over the green circle with center $O$, but now instead of a point, we&#39;ll invert the blue circle with center $C$ to the red circle.</p>
<div id="invertingCirclesFast" style="flex: 2; position: relative;"></div>

<center style="color: #666;">
<p>Again, we have the green circle $Ø$ as our inversion circle, but instead of just a point $P$ that we&#39;ll invert, we&#39;ll invert the entire blue circle with center $C$. Drag the different points around to see where our blue circle inverts to along with its center $C$ to $C&#39;$.</p>
</center>

<p>A lot of our rules with inverting points can easily give us an intuition for how our circles might invert. Points on a circle that are <em>inside</em> of our green inversion circle get flipped to be outside of it, and vice versa, and points <i>on</i> the inversion circle stay on the inversion circle (see how the red circle passes through the intersections of the green and blue circles). But, since we are looking at a group of points, some discrepancies between points obviously exist. For instance: distance. I have drawn both the center of our blue circle $C$ as well as its inversion $C&#39;$. But just by looking at it, it&#39;s obvious that there&#39;s no way $C&#39;$ can be the center of the blue circle&#39;s inversion! That&#39;s due to one key aspect of inversions: <strong>they do not preserve distances</strong>. </p>
<p>That should be apparent due to the actual inversion equation $|OP| \cdot |OP&#39;| = r^2$. This inverse relationship between the length of $OP$ and $OP&#39;$ is what really exaggerates inversions with very small or very big values of $OP$. In fact, this is why inverting a circle is so interesting as even though the distances get all messed up, <a href="https://math.stackexchange.com/questions/2425789/purely-geometric-proof-that-circles-invert-to-circles">a circle will still always invert into another circle</a>. Try inverting a square and you&#39;ll almost definitely get something that doesn&#39;t look like a square (<em>almost</em> definitely as if you align the center of the square with the center of the inversion circle, then that will result in another square; just try drawing it out and it will all fall into place). Even when it doesn&#39;t <em>look</em> like a circle, it really is! Try dragging the blue circle such that it intersects the center of our green inverting circle. You&#39;ll get something that looks like a line. While it acts as a line, we formally say that this is a really really big circle. Specifically, a circle with an infinitely large radius. It&#39;s a lot like how in calculus they say if you zoom in super far in on a curve it looks like a line, if you have a super big curve it locally looks like a line from our perspective.</p>
<h2 id="recap">Recap</h2>
<p>Ok, that was a lot, but what does this tell us? Well, just experimenting with inverting one circle tells us much about inversions and some properties they have. Let&#39;s write them out.</p>
<ol>
<li>Inversions do not preserve distances. We saw this with how a circle&#39;s center may not invert to the center of the inverted circle.</li>
<li>Every point $P$ has a unique inversion $P&#39;$ for any given circle of inversion $Ø$ with center $O$ and radius $r$. This may seem obvious, but it&#39;s important to be aware of as it leads to the next very important characteristic...</li>
<li><strong>Intersections and tangency between two or more shapes are preserved during an inversion</strong>. This fact is the one you want to hold onto the most for the upcoming sections. This should make sense as if two or more shapes share some point in common such as an intersection or tangent point $P$, that singular point has only one unique inverse $P&#39;$ which they must also share. And if all the points need to be connected to that point after the inversion, then we should expect to see that intersection/tangent point remain after an inversion.</li>
<li>Lastly, just as a neat fact, performing the same inversion twice results in nothing changing (the identity). You can think of this sort of like what happens when turning a shirt inside out twice: the first time the seams come out, but the second time it just goes back to how it started. Just going back to our formula $OP \cdot OP&#39; = r^2$, we know that $OP&#39;$ has some length that corresponds with $OP$ to keep that product the same. So, if we let $P \rightarrow P&#39;$ representing our first inversion, $P&#39;$ needs to go back to $P$ to keep the formula the same for the second inversion. This makes the function of an inversion a special function called an <a href="https://en.wikipedia.org/wiki/Involution_(mathematics)">involution</a>.</li>
</ol>
<hr>
<p>With the basics of inversion down, we are now ready to explore that animation from the very top of this post.</p>
<h2 id="steiner-s-porism">Steiner&#39;s Porism</h2>
<p>Steiner&#39;s Porism can sound a lot more complicated than it is, but I promise you the animation at the top explains everything. Let&#39;s break it down step by step. First, draw two non-intersecting circles with one inside the other. Second, draw a third circle that is tangent to the inside and outside circle. Third, draw as many circles as you can, each tangent to the inside, outside, and last circle you drew until no more can fit (we call this chain of circles a <em>Steiner chain</em>). <strong>Steiner&#39;s Porism</strong> states if the last circle is tangent to the first circle you drew, then there are an infinite number of chains that are tangent to one another (and if they are not tangent, then there are an infinite number of chains that are not tangent). So in the GIF above, since the chain of black circles are tangent to one another, the black circles are free to rotate like ball bearings in between the outer blue and inner red bounding circles and the chain will always link up to make one of the infinite configurations. It&#39;s pretty interesting, but how would someone ever prove this? That&#39;s where our friend inversion comes in.</p>
<p>Before we go any further though, let&#39;s quickly see if there&#39;s an easier version of this scenario. One of the main issues I first had when looking at this was the fact that the black circles rolling around didn&#39;t have to be the same size. Fortunately, there&#39;s an obvious case where we don&#39;t have to worry about that: when the two bounding circles are concentric.</p>
<div id="concentricVariableSteinerChain" style="flex: 2; position: relative;"></div>

<center style="color: #666;">
<p>Try dragging the red point to change the red circle&#39;s radius, and try rotating the black point to see the symmetry in the chains of circles.</p>
</center>

<p>When the circles share the same center, then Steiner&#39;s Porism becomes obvious: our set up now becomes symmetrical, so you can think of any starting point as a rotation of the original chain of circles. Since this is an easy fact to see, we can now use a key property of inversions to prove the general case for <em>any</em> pair of bounding circles:</p>
<blockquote>
<p>Intersections and tangency between two or more shapes are preserved during an inversion</p>
</blockquote>
<p>This is great for us, as then if we can find an inversion that turns our non-concentric circles into concentric circles, we can then use the fact that our tangents of the chain circles are preserved and use the obvious concentric circles case to close out the theorem. It may sound complicated, but think of it as a way to work backwards: if we can show we can turn any non-concentric circles into concentric ones, then the reverse is also true where there is some corresponding pair of concentric circles that invert to our original, non-concentric ones. Since the rules of tangency remain true between inversions, the rules for our circle chains remain as well (since they are only governed by tangents).</p>
<p>To find our desired circle of inversion, I&#39;ll present it as a series of steps that might not make sense immediately, but will definitely make sense retroactively. So, for now, I ask that you follow along with the steps and we&#39;ll discuss it at the end.</p>
<h3 id="step-1-find-the-radical-axis">Step 1: Find the radical axis</h3>
<p>The <strong>radical axis</strong> of a pair of circles is the line (or axis, I guess) that every point $P$ along the line is the same distance away from the <em>tangents</em> of the two circles. This sounds more complicated than it is and is much easier to see with a picture. Fortunately, it&#39;s not too hard to find <a href="https://www.cut-the-knot.org/Curriculum/Geometry/GeoGebra/RadicalAxes.shtml">with some simple geometry</a>. We&#39;ll draw the radical axis in green.</p>
<div id="radicalAxis" style="flex: 2; position: relative;"></div>

<center style="color: #666;">
<p>Although we can drag the green point anywhere, it always allows us to find an purple orthogonal circle.</p>
</center>


<p>Of course, the point $P$ in question has to be <em>outside</em> the two circles to be able to find tangents, but that&#39;s only a worry for intersecting circles (which we don&#39;t care about). I drew a purple circle center around $P$ to show that the tangents are in fact equal in length. This purple circle, however, has one notable property due to the 4 tangent lines it has as its radii: it is <strong>orthogonal</strong> to the red and blue circles, meaning that it intersects the red and blue circles at right angles. This is a result from the fact that <a href="https://en.wikipedia.org/wiki/Tangent_lines_to_circles#:~:text=The%20radius%20of%20a%20circle,the%20axis%20of%20the%20radius.">a circle&#39;s radius is perpendicular to its tangent</a>. Hold up a corner of a piece of paper and you&#39;ll see the right angles clearly. Speaking of orthogonal circles, that brings us to our next step.</p>
<h3 id="step-2-draw-two-orthogonal-circles-and-find-their-intersection">Step 2: Draw two orthogonal circles and find their intersection</h3>
<p>This step is easy enough since we&#39;ve basically already done half of it. We just need to draw another purple orthogonal circle as we&#39;ve done before, and then find their intersection. Our space will start to get cluttered quickly, so I&#39;ll remove the purple tangency lines, but just know that those are what determine our purple circles. We&#39;ll draw this intersection point in black.</p>
<div id="intersection" style="flex: 2; position: relative;"></div>

<center style="color: #666;">
<p>For any pair of red and blue circles, their orthogonal circles always intersect in the same two locations.</p>
</center>


<p>Here I&#39;ve selected the outermost intersection for clarity, but we&#39;ll see in just a second that either of the two intersections work just fine. First, it&#39;s worth noting that for a given configuration of outer blue and inner red bounding circles, the intersection points remain constant. No matter how you may slide those green points, the intersection point doesn&#39;t change. That should help cue you into its importance. </p>
<p>As a separate, interesting fact (that I haven&#39;t looked into enough), the centers of the red and blue circles are collinear with the two intersection points of the purple circles. Quirk aside, though, we can move onto the third and final step of this inversion circle finding process.</p>
<h3 id="step-3-draw-any-circle-at-the-chosen-intersection-point">Step 3: Draw any circle at the chosen intersection point</h3>
<p>Notice how I said &quot;any&quot; circle. A circle with any radius will suffice as our desired circle. This will be our circle to invert over! We&#39;re going to invert a total of four circles: of course, the red and blue ones, but we&#39;ll also invert the two helper, purple circles. The diagram might look a bit busy, but just remember that this building off the same diagrams from before; look for what&#39;s new in the graphic, and it will be less overwhelming.</p>
<div id="concentricInversion" style="flex: 2; position: relative;"></div>

<center style="color: #666;">
<p>Finally, we are able to invert our red and blue circles into concentric ones based on the black intersection point.</p>
</center>


<p>And just like that, we&#39;ve obtained our concentric circles just as we desired! Just to reiterate, because tangencies are preserved through our inversion, we can then draw our chain of tangent circles in the original blue and red bounding circles and know for a fact that they&#39;ll remain tangent after our inversion as well. Moreover, since the inversion turns our circles into concentric ones which is the nice symmetric case from before, Steiner&#39;s Porism is nicely proved as we know, once again, tangencies are preserved during an inversion.</p>
<h2 id="analysis">Analysis</h2>
<p>Ok, but why does this even work? I mean, yeah, it produces concentric circles, but our steps seemed so arbitrary. Why should it work? It has to do with our purple orthogonal circles. Remember, these circles are orthogonal meaning that they intersect our blue and red circles at right angles. Moreover, remember that by definition of our construction in <strong>Step 2</strong>, these orthogonal circles pass through the center of our black inversion circle. As we saw before, a circle passing through the center of the inversion circle means that these purple circles will invert into circles of infinitely-large radii (or lines, if you prefer). Lastly, we also know that, in addition to tangencies, intersections are preserved during an inversion. So, not only do we know that our inverted purple lines must intersect, but the intersections between the red and blue circles as well as the purple circles are also maintained. </p>
<p>So, we have two lines that intersect that need to be orthogonal to two other circles. What configuration allows this? The only way that a pair of lines can be orthogonal to a circle is if those lines are the radial line of the circle! So, both circles must share the same center of the intersection of the lines which ensure the lines become radial, and by definition of sharing a center, they must be concentric! Isn&#39;t that neat?</p>
<p>Also, this explains why our black intersection points of the orthogonal circles are invariant: regardless of what pair of orthogonal circles we use, there is precisely one center of inversion that maps both circles to have the same center (two, technically, but that just flips what circle is on the outside).</p>
<p>One thing worth noting, though, is that we get a solution even when the two circles are <em>not</em> contained within one another. If the two circles are non-intersecting and are completely separated from one another, we can still follow our procedure from before: we can find a radical axis of the two circles, which leads to our two purple orthogonal circles, that finally intersect at the center of our inversion circle. However, we now get a reversed solution with the red circle becoming the outer concentric circle instead of the inner one (this only happens as a result of the choice of intersection point of our orthogonal circles).</p>
<h2 id="conclusion">Conclusion</h2>
<p>Inversive geometry has all sorts of interesting quirks and facts to explore, and should be more well known than what it is. Maybe one day I&#39;ll touch on its connection to <a href="https://en.wikipedia.org/wiki/Inverse_curve">polar curves</a>. But anyways, this post wouldn&#39;t be complete if you couldn&#39;t build a Steiner chain of circles of your own, so below there is one last widget to experiment with tangent circles. I have left the special black inversion circle on the canvas just so you can see how all of our work to get concentric circles relates to any pair of nested, bounding circles. There&#39;s so much I had to gloss over to keep this short, such as the hidden conics in the path of the tangent circles, so I highly recommend skimming other articles such as <a href="https://mathworld.wolfram.com/SteinerChain.html">Wolfram MathWorld&#39;s</a> and even <a href="https://en.wikipedia.org/wiki/Steiner_chain">Wikipedia&#39;s</a> discussions on Steiner chains. With all things in math, this story is never over: Steiner&#39;s Porism has a projective geometry cousin known as <a href="http://olivernash.org/2018/07/08/poring-over-poncelet/index.html">Poncelet&#39;s Porism</a>, but that deserves its own post entirely some day. Inversive geometry is a simple yet powerful tool, and even just knowing the concept alone is useful to keep in your back pocket as you never know when you may come across <a href="https://en.wikipedia.org/wiki/M%C3%B6bius_transformation">something that has an uncanny resemblence to it</a>. Nevertheless, I hope you can at least leave this page with not just an appreciation of a cool bit of math, but a nice animation as well. As before, don&#39;t forget to try separating the circles to be outside of one another to get some strange, but special solutions to Steiner&#39;s Porism (if you&#39;re having trouble seeing the animation clearly, try reducing the radius of the black inversion circle).</p>
<div id="steinersComplete" style="flex: 2; position: relative;"></div>


<script src="/js/steiners/hook.js"></script>
<script src="/js/steiners/inversionIntro.js"></script>
<script src="/js/steiners/invertingCirclesFast.js"></script>
<script src="/js/steiners/concentricVariableSteinerChain.js"></script>
<script src="/js/steiners/radicalAxis.js"></script>
<script src="/js/steiners/intersection.js"></script>
<script src="/js/steiners/concentricInversion.js"></script>
<script src="/js/steiners/steinersComplete.js"></script>]]></description>
         <link>http://xperimex.github.io/blog/steiners-porism</link>
         <guid isPermaLink="true">http://xperimex.github.io/blog/steiners-porism</guid>
         <dc:creator><![CDATA[Adi Mittal]]></dc:creator>
      </item>
      <item>
         <title><![CDATA[Rotating Regulars and Greedy Grids]]></title>
         <description><![CDATA[Why grids love squares so much 

 <script src='https://cdnjs.cloudflare.com/ajax/libs/g9/1.0.16/g9.js'></script>
<script src="https://unpkg.com/mathjs/lib/browser/math.js"></script>

<p>We are all familiar with the idea of a grid. From making up the small pixels on our screen, to the compact city maps of New York, grids pop up everywhere due to the kind nature of the innate squares built into them; grids are extremely space efficient packing in squares above and below each other while still maintaining a sense of order. But, why do we grids love squares so much? Today, we&#39;ll look at a nice proof for why the square is the only regular polygon that can fit in a grid. </p>
<h2 id="tilted-thoughts-and-grid-properties">Tilted Thoughts and Grid Properties</h2>
<p>First, let&#39;s define what a grid is for us. A <strong>grid</strong> is a set of lattice points whose cardinal neighbors (up, down, left, right) are all equidistant from the given point. That&#39;s a lot more complicated than it sounds, but all you need to think of is a generic, <strong>square grid</strong> like you would find on a piece of graph paper.</p>
<!-- <div id="grid_example" style="flex: 2; position: relative;"></div>
<script src="/js/grid-polygons/grid_example.js"></script> -->
<p>No need to worry about any triangular or hexagonal grids (thank you organic chemistry). Obviously, squares fit in our grid, but how can any other regular polygon possibly fit? Well, remember, we don&#39;t necessarily need to only draw horizontal or vertical lines: we can easily draw tilted squares too.</p>
<p><div id="tilted_squares" style="flex: 2; position: relative;"></div></p>
<script src="/js/grid-polygons/tilted_squares.js"></script>

<p>Now that you know about tilted squares, here&#39;s nice puzzle to think about: given an $n \times n$ square grid, how many different squares can you draw? Check the <a href="#solution-to-squares-in-a-grid-puzzle">footnote</a> below if you want a solution, but just drawing it out will likely give you the intuition you need. Anyways, this tilted square reveals an important property of grids: rotating a lattice point by 90° around another point gives you a new, different lattice point. You can see this nicely with complex numbers. If you have a lattice point $a+bi$, a 90° rotation is equivalent to multiplying our number by $i\rightarrow i \cdot (a+bi) = -b + ai$. The coefficients remain integers, so if $(a,b)$ is a point, so is $(-b,a)$. </p>
<p>Another (less relevant for us) property is that if you know a line segment defined by 2 lattice points, and you are given a 3rd lattice point, you can find a 4th one by drawing a second line segment from your 3rd point (think of it like vector addition: if we know a vector and a point, we can find a new point by adding that vector the point). For the purpose of this post, though, just remember the former property.</p>
<h2 id="rotating-regular-polygons">Rotating Regular Polygons</h2>
<p>The proof that only regular polygon that a grid can define is a square is very simple, but very clever. Just as an example, we&#39;ll use a pentagon for demonstrative purposes. Let&#39;s assume that our regular $p$-gon (in our case, pentagon; I use $p$-gon due to poor variable naming later) exists in the grid.</p>
<p><div id="pentagon" style="flex: 2; position: relative;"></div></p>
<script src="/js/grid-polygons/pentagon.js"></script>

<p>If these 5 points that define our pentagon exists in the grid, then we should be able to generate 5 new, totally valid grid points by rotating them 90° around their neighbor.</p>
<p><div id="pentagon_rotate" style="flex: 2; position: relative;"></div></p>
<script src="/js/grid-polygons/pentagon_rotate.js"></script>

<p>Notice, though, that we just made another, smaller regular pentagon! ...Or did we? We can prove this quite simply geometrically (trust me, drawing it out and symmetry will guide you all the way through), but I don&#39;t want to draw anything right now so instead I&#39;ll show you a much more needlessly complicated, linear algebra approach to it (this will, though, give us specific numbers at the end of it). If you can accept this red pentagon is in fact a regular pentagon, just <a href="#skip">skip ahead</a>, but for now I&#39;ll present the proof. </p>
<p>If we can show that the new red pentagon lies on a parametric circle, we can then show that we our 5 angles to generate the original, black pentagon, maps to the new red pentagon. The way we generated our red pentagon was by taking a black point $v$, rotating it around its neighbor $t$ by 90° to land at $v&#39;$ as seen above. We can write this transformation as a product of 3 matrices: translating by $-t$, rotating 90°, then translating back by $+t$ (in a linear transformation, the origin remains fixed so the translations are our way to rotate about any point we want). If $v$ is a point of the form $(\cos\frac{2\pi n}{5}, \sin\frac{2\pi n}{5})$, then $t$ is the point $(\cos\frac{2\pi (n-1)}{5}, \sin\frac{2\pi (n-1)}{5})$ just as definition of being a pentagon on the unit circle, and $v$ and $t$ being neighboring points. So, our matrix equation of going from $v\rightarrow v&#39;$ is</p>
<center>
$
\begin{bmatrix}
1 &amp; 0 &amp; \cos\frac{2\pi (n-1)}{5} \\
0 &amp; 1 &amp; \sin\frac{2\pi (n-1)}{5} \\
0 &amp; 0 &amp; 1
\end{bmatrix}
\begin{bmatrix}
0 &amp; -1 &amp; 0 \\
1 &amp; 0 &amp; 0 \\
0 &amp; 0 &amp; 1
\end{bmatrix}
\begin{bmatrix}
1 &amp; 0 &amp; -\cos\frac{2\pi (n-1)}{5} \\
0 &amp; 1 &amp; -\sin\frac{2\pi (n-1)}{5} \\
0 &amp; 0 &amp; 1
\end{bmatrix}
\begin{bmatrix}
\cos\frac{2\pi n}{5} \\
\sin\frac{2\pi n}{5} \\
1
\end{bmatrix}
= v&#39;
$
</br></br>
$
\begin{bmatrix}
0 &amp; -1 &amp; \sin\frac{2\pi (n-1)}{5} + \cos\frac{2\pi (n-1)}{5}  \\
1 &amp; 0 &amp; \sin\frac{2\pi (n-1)}{5} - \cos\frac{2\pi (n-1)}{5} \\
0 &amp; 0 &amp; 1
\end{bmatrix}
\begin{bmatrix}
\cos\frac{2\pi n}{5} \\
\sin\frac{2\pi n}{5} \\
1
\end{bmatrix}
= v&#39;
$
</center>

<hr>

<p>Before we really dig into the matrix computations, take a look at the final column of that last matrix: it has something that looks like $\sin(x) + \cos(x)$ and $\sin(x) - \cos(x)$. These seem too nice not to have a formula for this sum and difference. So, before we go on, it will be worthwhile to see if we can condense those into nicer formulas. In fact, when you plot these functions, you do get what looks like nice sine waves.</p>
<p>Let&#39;s say we think it is some type of cosine curve.</p>
<center>
$\sin(x) + \cos(x) = A\cos(x + \phi)$
</center>

<p>$A$ is the amplitude of this new curve, and $\phi$ is the phase offset. Now, we fortunately have a well known angle addition formula for cosine.</p>
<center>
$\color{red}{1}\sin(x) + \color{red}{1}\cos(x) = A\cos(x + \phi) = \color{red}{A\cos(\phi)}\cos(x) \color{red}{-A\sin(\phi)}\sin(x)$
</center>

<p>This may seem hard to solve, but all we need to do now is match our coefficients (highlighted in <span style="color:red">red</span>). For the right hand side to equal the left hand side</p>
<center>
$A\cos(\phi) = 1$
<br>
$-A\sin(\phi) = 1$
</center>

<p>That way the $\cos(x)$ and $\sin(x)$ terms will be equal on either side. We can now square both equations and add them together to get</p>
<center>
$
\begin{array}{cccc}
  &amp; (A\cos(\phi))^2 &amp; = &amp; 1^2 \\
+ &amp; (-A\sin(\phi))^2 &amp; = &amp; 1^2 \\ \hline
  &amp; A^2(\cos^2(\phi) + \sin^2(\phi)) &amp; = &amp; 2
\end{array}
$
</center>

<p>Remembering that $\cos^2(\phi) + \sin^2(\phi) = 1$, we get that $A = \sqrt{2}$. Now we can solve for $\phi$ fairly quickly, too. Though, we&#39;ll have to be careful about range restrictions on $\cos^{-1}(x)$ and $\sin^{-1}(x)$, so we should corroborate them to make sure we get a value that satisfies both equations.</p>
<center>
$\begin{align}
A\cos(\phi) = 1 &amp; \rightarrow \phi = \frac{\pi}{4}, \color{red}{-\frac{\pi}{4}} \
\newline
-A\sin(\phi) = 1 &amp; \rightarrow \phi = \color{red}{-\frac{\pi}{4}}, \frac{5\pi}{4}
\end{align}$
</center>

<p>The only (reduced) angle that is satisfies both equations is $\phi = -\frac{\pi}{4}$. Putting it all together now, we can see that</p>
<center>
$\sin(x) + \cos(x) = \sqrt{2} \cos(x - \frac{\pi}{4})$
</center>

<p>In a similar manner,</p>
<center>
$\sin(x) - \cos(x) = \sqrt{2} \cos(x - \frac{3\pi}{4})$
</center>

<p>but we can make this more akin to our previous equation recalling that $\cos(x) = \sin(\frac{\pi}{2} - x)$.</p>
<center>
$\sin(x) - \cos(x) = \sqrt{2} \sin(\frac{\pi}{2} - (x - \frac{3\pi}{4})) = \sqrt{2} \sin(-x + \frac{5\pi}{4}) = \sqrt{2} \sin(x - \frac{\pi}{4})$
</center>

<p>Working with one term instead of the sum of two will make our life easier moving forward.</p>
<hr>

<center>
$
\begin{bmatrix}
0 &amp; -1 &amp; \sqrt{2}\cos(\frac{2\pi (n-1)}{5} - \frac{\pi}{4})  \\
1 &amp; 0 &amp; \sqrt{2}\sin(\frac{2\pi (n-1)}{5} - \frac{\pi}{4}) \\
0 &amp; 0 &amp; 1
\end{bmatrix}
\begin{bmatrix}
\cos\frac{2\pi n}{5} \\
\sin\frac{2\pi n}{5} \\
1
\end{bmatrix}
= v&#39;
$
</center>

<p>Unfortunately, this transformation matrix alone can&#39;t show us our net tranform is purely a rotation and scaling due to that third column (which indicates a translation). So, we will have to look at the individual components of $v&#39;$.</p>
<center>
$
\begin{bmatrix}
0 &amp; -1 &amp; \sqrt{2}\cos(\frac{2\pi (n-1)}{5} - \frac{\pi}{4})  \\
1 &amp; 0 &amp; \sqrt{2}\sin(\frac{2\pi (n-1)}{5} - \frac{\pi}{4}) \\
0 &amp; 0 &amp; 1
\end{bmatrix}
\begin{bmatrix}
\cos\frac{2\pi n}{5} \\
\sin\frac{2\pi n}{5} \\
1
\end{bmatrix}
= v&#39;
$
</br></br>
$
\begin{bmatrix}
-\sin\frac{2\pi n}{5} + \sqrt{2}\cos(\frac{2\pi (n-1)}{5} - \frac{\pi}{4}) \\
\cos\frac{2\pi n}{5} + \sqrt{2}\sin(\frac{2\pi (n-1)}{5} - \frac{\pi}{4}) \\
1
\end{bmatrix}
= v&#39;
$
</center>

<p>If $v&#39;$ truly is just a rotated and scaled version of a vertex of our original pentagon, then it follows that any $v&#39;$ should lie on a circle, just as $v$ does. So, we can use the Pythagorean identity that $(r\cos\theta)^2 + (r\sin\theta)^2 = r^2$ which implies that if we square the $x$ and $y$ components of $v&#39;$ and add them together, we should get a constant. For simplicity in writing, we&#39;ll use $\alpha = \frac{2\pi (n-1)}{5} - \frac{\pi}{4}$.</p>
<center>
$
(-\sin\frac{2\pi n}{5} + \sqrt{2}\cos \alpha)^2 + (\cos\frac{2\pi n}{5} + \sqrt{2}\sin \alpha)^2 =
$
</br>
$
\cos^2 \frac{2\pi n}{5} + \sin^2 \frac{2\pi n}{5} + 2\cos^2 \alpha + 2\sin^2 \alpha + 2\sqrt{2}(\cos\frac{2\pi n}{5}\sin \alpha - \sin\frac{2\pi n}{5}\cos \alpha)
$
</center>

<p>This may look like a pain to work with, but just grouping like terms and trigonometric identities clean this up real fast.</p>
<center>
$\begin{align}
1 + 2 + 2\sqrt{2}\sin(\alpha - \frac{2\pi n}{5}) &amp; = \
\newline
3 + 2\sqrt{2}\sin(-\frac{2\pi}{5} - \frac{\pi}{4}) &amp; = \
\newline
3 - 2\sqrt{2}\sin(\frac{2\pi}{5} + \frac{\pi}{4}) &amp; \approx 0.479852979
\end{align}$
</center>

<p>So it does simplify to a constant! This constant represents the radius$^2$ of the new circle the red pentagon lies on (based on the black pentagon&#39;s unit circle). Meaning, the radius of the circle the red pentagon lies on is $\sqrt{0.479852979} \approx 0.692714211$. To find the angle it is rotated by, we just find how far the first vertex ($n=0$) is rotated:</p>
<center>
$\theta = \tan^{-1}(\frac{y}{x}) = \tan^{-1}(\frac{1 - \sqrt{2}\sin(\frac{2\pi}{5} + \frac{\pi}{4})}{\sqrt{2}\cos(\frac{2\pi}{5} + \frac{\pi}{4})}) + \pi \approx 3.526465492$
</center>

<p>What&#39;s great about our linear algebra approach too is that it quickly generalizes for any regular $p$-gon! The only part of the result impacted by our choice of a pentagon is any appearance of $\frac{2\pi}{5}$. So if you wanted to do it for any regular $p$-gon, all you do is replace $\frac{2\pi}{5}$ with $\frac{2\pi}{p}$.</p>
<div id="skip">


<hr>
<p>To get back to the original point though, we have shown that a vertex $v$ on the unit circle under our specific transformation maps to a vertex $v&#39;$ on a scaled, rotated circle (and because it was all linear transformations, the scalings and rotations are uniform around the origin), which implies that our black pentagon maps to another regular pentagon in red. Since those vertices in red are valid points in the grid since we found them with 90° rotations of other, valid lattice points, we can find yet <em>another</em> set of 5 valid lattice points by doing the same operation again of rotating each vertex 90° around its neighbor.</p>
<p><div id="pentagon_rotate2" style="flex: 2; position: relative;"></div></p>
<script src="/js/grid-polygons/pentagon_rotate2.js"></script>

<p>With our previous logic, we know that this too is a regular pentagon, which again, allows us to find 5 <em>new</em> lattice points in our grid by doing the same operation of rotating around a neighbor by 90°... And again... And again... For as many new lattice points and pentagons as we want.</p>
<p><div id="pentagon_rotateF" style="flex: 2; position: relative;"></div></p>
<script src="/js/grid-polygons/pentagon_rotateF.js"></script>
<center style="color: #666;">
<p>Here are 15 nested pentagons; try dragging any of the vertices to zoom in and you can see they are just smaller, rotated regular pentagons.</p>
</center>

Ok, but why do we care? Remember, our grid is made up of a set of discrete points with some distance between each point. But, since we can always find 5 new lattice points that make a pentagon as small as we want by repeating the 90° rotation, that means that we can find a pentagon who's radius/sides are <i>smaller</i> than our grid point distances themselves. How do you draw a pentagon smaller than the space between points itself? It would be like trying to draw between the pixels of the screen you're reading this on, which is obviously impossible. So by contradiction, our initial assumption that a pentagon can exist in the grid must have been false. $\blacksquare$

While that shows it's impossible to have a pentagon in the grid, we still want to show that <i>only</i> the square can exist in the grid. Recall our formula for the radius of the bounding circle of our pentagon (if you skipped ahead originally go back to see where this comes from):

<center>
$r(p) = \sqrt{3 - 2\sqrt{2}\sin(\frac{2\pi}{p} + \frac{\pi}{4})}$
</center>

Since we were working with the example of a pentagon, originally $p=5$ for us. The reason why our pentagons kept shrinking is because $r < 1$ for $p=5$. We need to show all regular polygons except the square results in a shrinking radius. In other words, we need to show that $r<1$ for all $p>4$. First, let's note the value of $p=4$ to start:

<center>
$\begin{align}
r(4) & = \sqrt{3 - 2\sqrt{2}\sin(\frac{2\pi}{4} + \frac{\pi}{4})} \\
<!-- \newline -->
& = \sqrt{3 - 2\sqrt{2}\cdot\frac{\sqrt{2}}{2}} \\
<!-- \newline -->
& = \sqrt{3 - 2} \\
<!-- \newline -->
& = 1
\end{align}$
</center>

This is why the square works out as it never shrinks as a 90° rotation around neighbors just maps one vertex to another already existing one. Now, let's examine the term $\sin(\frac{2\pi}{p} + \frac{\pi}{4})$. As $p$ gets larger than 4, the angle we're taking the $\sin$ of is not only bounded to quadrant 1, but is also getting smaller and closer to $\frac{\pi}{4}$, but never quite equal. This results in a $\sin$ value slightly larger than $\frac{\sqrt{2}}{2}$, which makes the difference $3-2\sqrt{2}\sin(\frac{2\pi}{p} + \frac{\pi}{4}) < 1$. Here's the graph of $r(p)$ as well as the bound of $r=1$.

</br></br>
<img src="/img/grid-polygons/regPolygonVRad2.png">
</br>

Some might look at this graph and see an obvious flaw: what about the case of the equilateral triangle though ($p=3$)? Yes, technically it has an $r>1$ and this does actually result in it expanding out.

<div id="triangle_rotate" style="flex: 2; position: relative;"></div>
<script src="/js/grid-polygons/triangle_rotate.js"></script>

<p>If the points expand out, we can&#39;t really say much about it existing in the grid or not since we only have a minimum bound on the distance between lattice points. But, there was a second property I glossed over regarding grids:</p>
<blockquote>
<p>If you know a line segment defined by 2 lattice points, and you are given a 3rd lattice point, you can find a 4th one by drawing a second line segment from your 3rd point.</p>
</blockquote>
<p>This property allows the equilateral triangle to be turned into the equivalent case of a hexagon, leading it to a case where $p&gt;4$ and hence an $r&lt;1$, indicating that an equilateral triangle, too, is impossible to draw within the grid.</p>
<p>Another neat little fact is the bend at $p=8$; an octagon has the smallest bounding radius for the 90° neighbor rotations (since that makes the $\sin$ term go to 1). But after that, $r(p)$ starts to increase. How can we know it won&#39;t equal or exceed 1? Well, no matter how big $p$ is, $\frac{2\pi}{p} + \frac{\pi}{4}$ will always be greater than $\frac{\pi}{4}$. Just thinking about it though leads to an interesting thought: what about at the limit of $p\to\infty$?</p>
<center>
$\lim\limits_{p\to\infty} \sin(\frac{2\pi}{p} + \frac{\pi}{4}) = \sin(0 + \frac{\pi}{4}) = \frac{\sqrt{2}}{2}$
</center>

<p>Which as we saw, would lead to an $r$ value of 1. So, according to this limit, an infinite sided $p$-gon, better known as the circle, is possible... <em>at the limit</em>. You&#39;ll get better and better approximations of the circle the more sides you add, but this essentially turns our grid into lattice points that are infinitely close together, which ruins the point of the grid in my opinion. So, it&#39;s up to you if you think a circle can exist in a grid, but an interesting thought nonetheless.</p>
<h2 id="other-grids-">Other Grids?</h2>
<p>Earlier I mentioned that we did&#39;t need to worry about triangular or hexagonal grids, but what if we did?</p>
<p><div id="trihex_grid" style="flex: 2; position: relative;"></div></p>
<p><script src="/js/grid-polygons/trihex_grid.js"></script></p>
<center style="color: #666;">
<p>The triangular (left) and hexagonal (right) grids are less obvious for what other regular polygons they can fit.</p>
</center>

<p>Fortunately, this just requires tweaking our matrix equation from before a little bit: instead of rotating by 90°, we now rotate by 60° and 120° for the triangular and hexagonal grids respectively. In general, if we want to rotate by $\theta$ radians (easy conversion from degrees) around a neighboring point for a regular $p$-gon, the vector for $v&#39;$ in terms of $v$ is </p>
<center>
$
\begin{bmatrix}
x \\
y \\
1
\end{bmatrix}
=
\begin{bmatrix}
\cos(\theta + \frac{2\pi n}{p}) + 2\sin(\frac{2\pi (n-1)}{p} + \frac{\theta}{2})\sin(\frac{\theta}{2}) \\
\sin(\theta + \frac{2\pi n}{p}) - 2\cos(\frac{2\pi (n-1)}{p} + \frac{\theta}{2})\sin(\frac{\theta}{2}) \\
1
\end{bmatrix}
= v&#39;
$
</center>

<p>Finding $r=\sqrt{x^2 + y^2}$ again reveals that</p>
<!-- Thanks WolframAlpha: https://www.wolframalpha.com/input/?i=%28cos%28theta+%2B+2pi*n%2Fp%29+%2B+2sin%282pi%28n-1%29%2Fp+%2B+theta%2F2%29sin%28theta%2F2%29%29%5E2+%2B+%28sin%28theta+%2B+2pi*n%2Fp%29+-+2cos%282pi%28n-1%29%2Fp+%2B+theta%2F2%29sin%28theta%2F2%29%29%5E2 -->
<center>
$r_\theta (p) = \sqrt{3+2\cos(\theta + \frac{2\pi}{p}) - 2\cos(\theta) - 2\cos(\frac{2\pi}{p})}$
</center>

<p>...which is in fact a constant. So rotations of <i>any</i> angle around neighboring points output more regular polygons. </p>
<p><div id="pentagon_rotate_angle" style="flex: 2; position: relative;"></div></p>
<p><script src="/js/grid-polygons/pentagon_rotate_angle.js"></script></p>
<center style="color: #666;">
<p>Try rotating one of the red dots to watch the regular pentagon grow and shrink according to the angle you rotate around its neighbor.</p>
</center>

<p>As before, we can plot this function to see what regular polygons have a bounding radius less than one for each grid:</p>
<!-- </br></br> -->
<p><img src="/img/grid-polygons/hexTriCompare2.png">
<!-- </br> --></p>
<p>Even though it would appear that no hexagons can be made in the triangular grid as they have a bounding radius $r_{\frac{\pi}{3}}(6)=0$. However, the point they actually collapse into is valid vertex of the triangular grid. This is because that&#39;s a type of definition of the triangular grid: draw a hexagonal grid and place extra points in the center of each hexagon. So again, the only apparent shapes in that can be contained in the triangular and hexagonal grids unfortunately appear to be none other than just the equilateral triangle and regular hexagon themselves.</p>
<hr>
<p>This post was inspired by a Mathologer video discussing an application of <a href="https://youtu.be/sDfzCIWpS7Q">shrinking polygons</a> and this out-of-the-box thinking that is so cool. Part way through the video, he glosses over the reasoning behind why the shrinking polygons are similar, so this is my own take on that portion of the video.</p>
<h3 id="solution-to-squares-in-a-grid-puzzle">Solution to squares in a grid puzzle</h3>
<p>As I said, drawing it out is your best bet. Let&#39;s start with how many $1 \times 1$ squares there can be in an $n \times n$ grid. Well, it&#39;s just $(n-1)^2$ by definition of the size of the grid (remember, $n$ refers to the number of dots, so there are only $(n-1) \times (n-1)$ squares). How about $2 \times 2$ squares? Well, we have eliminated a possible row and column from which we can place the square, so there are $(n-2)^2$ total $2 \times 2$ squares. You might be tempted to say that there are $\sum_{i=1}^{n-1} (n-i)^2$ total squares (where we are individually counting every $i\times i$ square up to $n-1$), but you can&#39;t forget that there are tilted squares too. The trick here is now that you have all the non-tilted squares, you just need to find how many possible tilted squares can be contained in a non-tilted square. In a $1 \times 1$ square, there is no room to tilt a square in it, so we move on. In a $2 \times 2$ square, there is exactly one extra lattice point to tilt on, so we add a factor of $2$ to our count of $2\times 2$ squares $\rightarrow 2(n-2)^2$. Similarly for a the $3 \times 3$ squares, we have 2 new lattice points we can tilt to, tripling our count $\rightarrow 3(n-3)^2$ squares. So finally, we can write it as a final sum of $\sum_{i=1}^{n-1} i(n-i)^2 = \frac{1}{12}(n^2)(n^2-1)$ total squares for an $n \times n$ grid.</p>
]]></description>
         <link>http://xperimex.github.io/blog/grid-polygons</link>
         <guid isPermaLink="true">http://xperimex.github.io/blog/grid-polygons</guid>
         <dc:creator><![CDATA[Adi Mittal]]></dc:creator>
      </item>
      <item>
         <title><![CDATA[Quarantine Quandaries and Variable Vaccines]]></title>
         <description><![CDATA[Modelling the past 17 months in 17 minutes 

 <script src='https://cdnjs.cloudflare.com/ajax/libs/g9/1.0.16/g9.js'></script>
<script src="https://unpkg.com/mathjs/lib/browser/math.js"></script>

<p>COVID-19 is one of those events that will likely not just define the way people will interact with each other, but likely entire socieities. I wouldn&#39;t even be surprised to see this pop up in an AP US History textbook in a decade just for how long the pandemic has been drawn out for. So it should be no surprise that from the first month of the pandemic, a vaccine was the only thing on people&#39;s minds. I mean, just look at this graph depicting the number of total coronavirus cases in the U.S. <em>alone</em>.</p>
<p><img src="/img/quarantine-quandaries/us-state-trends.png"></p>
<center style="color: #666;">
<p>Data as reported by the <a href="https://covid.cdc.gov/covid-data-tracker/#trends_dailytrendscases">CDC</a> (updated as of July 15th)</p>
</center>

<p>It took around 2 months to hit a million cases in the U.S., and another 3 months to reach 5 million cases. That&#39;s the issue with pandemics: they explode at a rate faster than we can realize. So, today, I want to talk a little bit about different types of disease models, and how these can educate ourselves on the right preventative courses of action.</p>
<h2 id="the-sir-model-2-ways">The SIR Model 2 Ways</h2>
<p>The <strong>S</strong>usceptible <strong>I</strong>nfected <strong>R</strong>ecovered Model of disease spread groups individuals into 3 boxes and relates them to show how each box grows or diminishes over time: susceptible means that you are currently healthy but are vulnerable to the infection; infected means just that and indicates a current illness; and while recovered doesn&#39;t necessarily mean you overcame the disease, it means you are unable to spread the disease anymore (sobeit proper recovery and developed immunity, but also the unfortunate case if you die since both are no longer disease vectors). This sounds like the perfect use for a Markov chain (here&#39;s a <a href="http://xperimex.com/blog/metropolis-hastings/#markov-chains">refresher if you need one</a>)! Our Markov chain will have 3 states being the aforementioned susceptible, infected, and recovered, and will follow a transition model as such:</p>
<p><img src="/img/quarantine-quandaries/markovSIR2.png"></p>
<center style="color: #666;">
<p>The SIR Markov chain model</p>
</center>

<p>Let&#39;s say everyone starts out as susceptible; we can write our initial population as $N$, and the initial distribution of those $N$ people as $P = \begin{bmatrix} N &amp; 0 &amp; 0 \end{bmatrix}$ for $N$ susceptible, 0 infected, and 0 recovered.</p>
<p>With that out of the way, let&#39;s think about the above Markov chain. If you are currently susceptible, each day there&#39;s a chance you might become infected. Let&#39;s call this probability $\beta$ as the average chance of getting infected. At the same time though, if you are smart and act carefully, you might not become infected, and this will be $1-\beta$. Similarly if you&#39;re infected, there&#39;s a chance you might (positively or otherwise) overcome the disease! We&#39;ll call this probability $\gamma$, and the chance of not recovering $1-\gamma$ (you can think of $\gamma$ by taking its inverse: $\frac{1}{\gamma}$ is the average number of days for a recovery to occur). Finally, if you&#39;re recovered, that&#39;s the end of your journey, as once recovered you&#39;re always recovered. This can be condensed into the simple transition matrix below.</p>
<center>
$
M = 
\begin{bmatrix}
1-\beta &amp; \beta &amp; 0 \\
0 &amp; 1-\gamma &amp; \gamma \\
0 &amp; 0 &amp; 1
\end{bmatrix}
$
</center>

<p>With that, let&#39;s run a trial with infectivity $\beta=.4$ and $\gamma=\frac{1}{5}$ (we expect an infection to take 5 days to recover). So on Day 0, everyone is healthy and (ironically) susceptible to our disease. The following Day 1, people are interacting and enjoying themselves, unbeknown to them that they are spreading a new contagion. Day 1 results in $PM = \begin{bmatrix} 800 &amp; 200 &amp; 0 \end{bmatrix}$, which makes sense as we expected 20% to become infected. We can track each state of S, I, and R and plot them accordingly across the span of a month.</p>
<p><img src="/img/quarantine-quandaries/SIRMarkov.png"></p>
<center style="color: #666;">
<p>Evolution of the SIR Markov chain as percent of the population</p>
</center>

<p>For such a simple model, it&#39;s not bad, but there are some obvious flaws. For starters, the infected population doesn&#39;t really infect others; all infections stem from random appearances in the susceptible population. This is why by the end of the 30 days, we have 0 susceptible and only recovered, since infections don&#39;t require infected to be present which is kind of odd (notice how our initial population was <em>only</em> susceptible and yet infected pop up). We can do better.</p>
<p>While Markov chains were appealing due to the nature of having 3 states, what we really want to focus on is the relationships between the 3 states: if there are lots of infected people, that should increase the rate at which others get infected. Since we&#39;re looking at how the value of one box (infected people) affect the rate at which the other boxes change (how fast susceptible and recovery decrease/increase), perhaps we should try a system of differential equations. Instead of states, we&#39;ll now have 3 different functions: $S(t)$, $I(t)$, and $R(t)$, which returns the number of susceptible, infected, and recovered at a time $t$. If you&#39;re not familiar with differential equations, don&#39;t worry, this section will be brief. The idea behind differential equations is that sometimes it&#39;s hard to exactly quantify a function or value, but we know how the function <em>changes</em> relative to another value. See the first few minutes of this <a href="https://youtu.be/p_di4Zn4wz4">video</a> if this idea intrigues you and for some nice opening examples. Besides, you already know more or less what the equations look like we know what the function should look like.</p>
<center>
$
\begin{align}
\frac{dS}{dt} &amp; = -\textrm{Number of new infections} \
\newline
\frac{dI}{dt} &amp; = \textrm{Number of new infections} - \textrm{Number of new recovered} \
\newline
\frac{dR}{dt} &amp; = \textrm{Number of new recovered}
\end{align}
$
</center>

<p>That&#39;s really all there is to them. The specific math behind it looks more complicated than it is, but keeping the above in mind will make it much clearer.</p>
<center>
$
\begin{align}
\frac{dS}{dt} &amp; = -\frac{\beta S}{N} I \
\newline
\frac{dI}{dt} &amp; = \frac{\beta S}{N} I - \gamma I\
\newline
\frac{dR}{dt} &amp; = \gamma I
\end{align}
$
</center>

<p>I like to think of it that of that the fraction of the vulnerable people $\frac{S}{N}$ have a $\beta$ chance of being infected, which is scaled up by the number of infected people $I$. That makes sense for number of new infected people. Similarly, if the average chance of recovery is $\gamma$, then you should expected a proportion of $\gamma$ infected people to recover ($\gamma I$). Last important fact to note is what happens when we add these equations together:</p>
<center>
$\frac{dS}{dt}+\frac{dI}{dt}+\frac{dR}{dt}=0$
</center>

<p>No matter how the 3 different categories of people evolve over time, the net change between all of them will be 0, meaning our total population remains the same over time (which is good since we don&#39;t want people appearing and disappearing out of nowhere). Let&#39;s watch the scenario unfold once more with $N=1000$ with a distribution of $P = \begin{bmatrix} 999 &amp; 1 &amp; 0 \end{bmatrix}$ (<i>someone</i> has to start the pandemic), $\beta=.4$, and $\gamma=\frac{1}{5}$.</p>
<p><img src="/img/quarantine-quandaries/SIRDifferential.png"></p>
<center style="color: #666;">
<p>Evolution of the SIR differential equations as percent of the population</p>
</center>

<p>That&#39;s more like that famous curve. It may not be as drastic as the 10 day everyone-is-infected model as the Markov chain we tried earlier, but it&#39;s definitely much more realistic. A single person was able to infect about 800 people across only a couple of months, which is still scary fast. </p>
<h2 id="-r-and-disease-containment">$R$ and Disease Containment</h2>
<p>Just as famous as a curve this may be, you likely have heard of the idea of $R$ and $R_0$ too. $R$ is the <strong>reproduction number</strong> of a disease/virus that tells you on average, how many people an infected person will spread the disease to. If $R&gt;1$, then you get the epidemic issue, where the disease is spreading exponentially as each person is giving more people than just themselves the disease. When $R=1$, you have an <em>endemic</em> where the disease is neither spreading nor being contained. When $R&lt;1$, then you have a contained virus that is decaying throughout a community. $R_0$ is just the $R$ value at the start of the outbreak, and can be found with the formula $R = \frac{\beta}{\gamma}$. In our simulation, $R_0 = \frac{.4}{.2} = 2$. So if we wanted to contain this disease, we want to find how many infections we need to contain for $R&lt;1$. Since $R_0 \cdot .5 = 1$, we only need to contain 50% of infections to contain the outbreak!</p>
<p><img src="/img/quarantine-quandaries/SIRDifferentialHerd.png"></p>
<p>You can see as soon as there is less than 50% of the population left to infect, infections start to decline—not end, but decline. You can also reduce infectivity by wearing preventative measures (i.e. masks) or getting the appropriate immunization against the disease (i.e. vaccines). If you want to read more about this model and more of its intricacies, Nicky Case wrote a very nice <a href="https://ncase.me/covid-19/">interactive article</a> about it.</p>
<h2 id="small-scale-vaccinations-and-graph-theory">Small Scale Vaccinations and Graph Theory</h2>
<p>While we did find a nice model to represent disease spread, the SIR model only is really nice for analyzing very <em>big</em> communities. With the SIR model, we assume everyone interacts with enough people so that infected people can always target a susceptible person if they need to in this very dense network of people. </p>
<p>Most people, though, only regularly interact and really care about those immediately in their social circles. In this small scale, such as say, a neighborhood or even a friend group, people do <em>not</em> interact with others equally. Some are more introverted and interact with only a few people, and some are extroverted beacons that interact with most of the group. This changes the dynamics of disease spread a lot as obviously those who are more outgoing and meet more people will be more at risk of being infected than someone who only talks to a few people. As such, we&#39;ll need a different approach than the SIR model.</p>
<p>In order to model connections between people we&#39;ll use a <strong>graph</strong>. A graph in this case is not the standard parabola of $f(x) = x^2$, but rather it is a visual tool consisting of two parts: there are <strong>nodes</strong> which are dots (to represent people here), and <strong>edges</strong> that are lines that connect nodes (to represent interactions or friendships).</p>
<p><img src="/img/quarantine-quandaries/exampleGraph (2).png"></p>
<center style="color: #666;">
<p>Example of a graph that may represent the individual friendships in a clique</p>
</center>

<p>As in most groups, we have a couple of people at the center connected to quite a few people, and some on the edge of the circle regularly interacting with as few as 2 people. This is a really helpful representation as now not only can we watch <em>where</em> the virus spreads, but we also have a direct way to implement small scale prevention tactics as we can see specifically who is infected. Ideally, we would vaccinate everyone in this group and make sure (consequential) disease spread can occur, but that might not happen. So, <strong>if we could only vaccinate, say, 25% of this group, who would you vaccinate to minimize a disease vector?</strong> There are some obvious candidates such as the nodes with the most connections, but what is the <em>best</em> way Let&#39;s leave our <span style="color:green">susceptible</span> people in green and <span style="color:red">infected</span> in red, but we&#39;ll add a new purple node to indicate <span style="color:purple">vaccinated</span>.</p>
<p><img src="/img/quarantine-quandaries/exampleVax.png"></p>
<center style="color: #666;">
<p>Randomly vaccinating 5 of the 20 people in the network. Can we do better?</p>
</center>

<p>Before we talk strategies, let&#39;s be clear about some of the assumptions made for simplicity sake.</p>
<ul>
<li>Vaccinations are 100% effective both ways, completely negating the possibility of infection of and transmission from the vaccinated person as if fully immune.</li>
<li>Edge lengths do not matter; if someone is connected to another person, we assume that that edge will act the exact same way as all other interactions and edges. This ensures a contant $\beta$.</li>
<li>Dying and recovering from the disease will be again treated the same under an overarching &quot;Recovered&quot; state, in which the affected person becomes fully immune. </li>
<li>An infected person &quot;recovers&quot; after only a single day ($\gamma = 1$) since a) it will ensure our simulation can spit out some numbers at the end as it&#39;s hard to <em>completely</em> protect an entire network of people, and b) our program wasn&#39;t written the most efficiently. </li>
</ul>
<p>As before, we want to find strategies ways to reduce $R_0$. But, what is $R_0$ in this case? Well, remember $R_0$ is just the average number of transmissions a single infected person will instigate. So, we can approximate this with the average number of edges an infected node has, multiplied by the infectivity. Since we can&#39;t change the infectivity rate ($\beta$), the only way we can lower it is by removing possible edges for infected people to transmit across. So, let&#39;s look at different strategies that are both really good and really bad at removing edges from our graph.</p>
<ol>
<li><span style="color:blue"><strong>Random</strong></span>: Realistically, vaccinating people randomly seems like a bad idea. In a simulation, though, it&#39;s never a bad starting point.</li>
<li><span style="color:orange"><strong>Random then neighbors</strong></span>: Here, we start with a single random person to vaccinate, then only vaccinate people connected to an already vaccinated person. If your friend got vaccinated, why shouldn&#39;t you?</li>
<li><span style="color:teal"><strong>Most connected</strong></span>: This is the obvious solution. If we want to reduce edges efficiently, why don&#39;t we vaccinate the nodes with the most edges connected to the most people?</li>
<li><span style="color:black"><strong>Most connected non-neighbors</strong></span>: This is a spin on the last one. We want to vaccinate the most connected people, but why not spread them out a bit? We pick the highest connected node to vaccinate, and then proceed to vaccinate the next highest node that is not connected to a vaccinated person.</li>
<li><span style="color:pink"><strong>Least connected</strong></span>: This one is more of a why not scenario. It&#39;s like the previous two strategies but reversed: find the loners of the group and vaccinate them.</li>
</ol>
<p>Again, we&#39;ll randomly vaccinate $\approx$25% of our population (50/100, 100/200, 200/400, and 400/800 people/total connections) according to our strategies above. We&#39;ll also infect 10% of our population with the contagion of your choosing with the same infectivity at $\beta = .4$ as before. We&#39;ll do 10 trials per population size, and average them to get a rough estimate at how each strategy faired.</p>
<p><img src="/img/quarantine-quandaries/results (1).png"></p>
<p>Unsurprisingly, vacciating the most connected nodes without restriction faired the best; closing off as many routes of infection as fast as possible led to only about 10% of non-vaccinated people getting infected. Following close behind is most connected non-neighbors strategy. Even though we tried spreading out vaccinations since the edge between two vaccinated people doesn&#39;t require two does of the same vaccine, by nature of being a popular node, it is likely connected to other popular nodes too. So in reality, we are removing fewer edges than we could be just vaccinating the most popular nodes. It&#39;s for this reason why our orange strategy of randomly vaccinating one person then its neighbors was such a bad strategy: not only do we not know if we&#39;re vaccinating a well connected person, but we&#39;re wasting vaccines but doubly protecting edges between neighbors. Since reducing the edge count is our only form of reducing $R_0$, this is a very bad strategy. What is surprising though, is that vaccinating the least connected people was almost as good as random. Since unpopular people can only be connected to so many people, they tend to be pretty spread out removing a fair number of edges between all the vaccinated people.</p>
<h2 id="what-next-">What next?</h2>
<p>Honestly, our graph model isn&#39;t all that bad considering how simple it is, but let&#39;s look at some nice upgrades we can hand over to it.</p>
<h3 id="graph-generation">Graph Generation</h3>
<p>This was originally made as a school project, so we generated our graph by taking some number of edges and placing them randomly between nodes for simplicity in presentation. However, these obviously aren&#39;t the only types of networks. A prominent one for modelling interactions between people is the <strong>Erdös-Rényi</strong> graph. For $n$ nodes, there are $n \choose 2$ possible pairings of nodes for edges. In an ER graph, we flip a weighted coin to accept an individual edge, and the final result is just the collection of edges we added. If our acceptance probability is $p$, then we would expect the graph to have a total of ${n \choose 2}p$ edges, each node to have on average $p(n-1)$ connections. In this network, people are approximately as popular as others (since our coin flip method leads to a binomial distribution with few super popular or super unpopular people).</p>
<p><img src="/img/quarantine-quandaries/exampleER (1).png"></p>
<center style="color: #666;">
<p>An Erdös-Rényi graph with an average connection of 4.8. Look how nice and even this graph is.</p>
</center>

<p>Another type of graph is the <strong>Barabási-Albert</strong> type graph. The idea with this network is that people tend to be connected to a distinct, central &quot;hub&quot; of a few people that make up most of a network. The idea is that you start with a small network of $m$ people/nodes to begin with. At each step, you add a new node and connect it to another person $i$ with probability $p_i = \frac{E(i)}{\sum_jE(j)}$ where $E(x)$ is the number of edges for node $x$ and $j$ represents all other nodes. The idea is that if $E(i)$ is really big (i.e. a super popular person), then you&#39;ll have a much bigger probability to connect to that person over someone who only has a few connections. Wouldn&#39;t you want to hang out with the cool kids too? You can give $i$ as many connections as you want, so long as it&#39;s less than $m$ (think about the first new node: how can someone have 10 different friends in a group of 5?).</p>
<p><img src="/img/quarantine-quandaries/exampleBA (1).png"></p>
<center style="color: #666;">
<p>A Barabási-Albert graph where each new node gets 2 connections to the existing network. Can you see the clusters of the graph?</p>
</center>

<p>If you want to explore this more, the <a href="https://www.complexity-explorables.org/explorables/facebooked-flu-shots/">inspiring article</a> that led to this project analyzes these 2 exact graphs in the exact problem we discussed above, going a bit more in depth with the idea of the counterintuitive <a href="https://en.wikipedia.org/wiki/Friendship_paradox">friendship paradox</a>.</p>
<h3 id="new-vaccination-schemes">New Vaccination Schemes</h3>
<p>We looked at a very specific set of vaccination parameters, namely relying on all edges are treated equally and that the number of edges a node has is constant. In reality, people don&#39;t interact with each other equally, so instead of having a generic edge, we could implement an edge <strong>weighting</strong>. This quality would add a number between 0 and 1 to each edge to represent how &quot;friendly&quot; two people are with each other. We could then simulate the difference between best friends and mere colleagues interacting that may have more or less of a chance to spread a virus. The other aspect to consider was updating edge counts. Ideally we would only want to count a vaccine&#39;s candidate&#39;s number of edges to <em>vulnerable</em> people, not vaccinated onr infected people too, with counts updating after every vaccination. Then we could focus on protecting people specifically.</p>
<p>The final problem I wanted to talk about what the goal of vaccines are in a network. As we said, it&#39;s about removing edges efficiently, but some edges are definitely worth more than others. Imagine you have two friend circles, with exactly one mutual person between them. Even if that mutual friend has only two edges, vaccinating him would close that bridge between the two friend circles, isolating the virus into only one of them.</p>
<p><img src="/img/quarantine-quandaries/barbell.png"></p>
<center style="color: #666;">
<p>Vaccinating the literal middle-man isolates the two groups</p>
</center>

<p>This searching for a way to split our graph in two parts with the fewest number of edges removed is called the <strong>sparsest cut problem</strong>. If we can find the (usually approximate) sparsest cut, we can divide our graph in two and attempt to isolate the virus in only a singular bubble. Before, we were looking to remove something known as <a href="https://en.wikipedia.org/wiki/Hamiltonian_path"><strong>Hamiltonian paths</strong></a>, where you can&#39;t connect any one node to another. Here, we are trying to isolate the virus into a smaller bubble.</p>
<p><img src="/img/quarantine-quandaries/sparsestCut (1).png"></p>
<center style="color: #666;">
<p>Sparsest cut of a random ER graph that approximately cuts the graph in half</p>
</center>

<p>So here we would want to vaccinate everyone on the border of the yellow-purple divide to make the sparsest cut a reality. Of course, this only works if you have enough vaccines AND if your sparsest cut splits the graph in half evenly. This strategy can be used recursively on the two sub-graphs, so the more vaccines you have, the better this strategy works.</p>
<h2 id="conclusion">Conclusion</h2>
<p>I hope this brought some light to the epidemic math that goes on behind the scenes of so many news articles, but more importantly showed you the power of modelling situations not just in different ways, but creative ones as well. Graph theory in particular has such widespread applications, often just thinking of something simply with connections can allow you to borrow from its variety of tools and techniques.</p>
]]></description>
         <link>http://xperimex.github.io/blog/quarantine-quandaries</link>
         <guid isPermaLink="true">http://xperimex.github.io/blog/quarantine-quandaries</guid>
         <dc:creator><![CDATA[Adi Mittal]]></dc:creator>
      </item>
      <item>
         <title><![CDATA[Treeline Riddles and Triangular Rends]]></title>
         <description><![CDATA[A puzzle to test in the forest 

 <p><strong>If you break a stick at 2 uniformly random points into 3 segments, what&#39;s the probability you can form a triangle out of those 3 segments?</strong></p>
<p>As with all puzzles, drawing something always helps.</p>
<p><img src="/img/triangle-puzzle/stickSetup.png"></p>
<center style="color: #666;">
<p>Label the ends of the stick to be 0 and 1, and we&#39;ll make the first break at point $x$.</p>
</center>

<p>The key to this puzzle is to use the <strong>triangle inequality</strong>: no side of a triangle can be longer than the sum of the other two.</p>
<p><img src="/img/triangle-puzzle/triangleIEQ.png"></p>
<center style="color: #666;">
<p>The triangle inequality visualized.</p>
</center>

<p>So, that means that no segment can be longer than half the length of our stick. Now, we can start solving the puzzle. Without loss of generality, make the first break at point $x$ between 0 and .5 to ensure our first break is on the left side (if it&#39;s not within this range, it&#39;ll be some symmetric case on the right half of the stick). Our left half of the stick is already less than .5, so that&#39;s good, but that means our second break <em>must</em> be on the right half, as otherwise that will be a leg that will be greater than .5, and that&#39;s no good. The probability our second break will be on the right half of the leg is equal to the length of that segment over the total line (since it&#39;s uniformly random): $\frac{1-x}{1}$. Let&#39;s analyze that longer leg now.</p>
<p><img src="/img/triangle-puzzle/longLegFeasible.png"></p>
<center style="color: #666;">
<p>The feasibility region in red shows the location of a valid cut to ensure it does not make a segment longer than .5 units.</p>
</center>

<p>We can&#39;t make a cut at or further than the .5 mark on the segment for the obvious reason: it would make a leg longer than .5, breaking the triangle inequality. For a similar reason, we can&#39;t make a cut at $1-x-.5$ or earlier, as that will make a leg on the right side longer than .5 too. We need a cut in between those two boundaries. Just like we found the probability for making a cut on this longer leg to begin with, if we can find the length of that feasibile region and divide that by the length of the leg, that will give us the probability for making a good cut here. The length of the red feasible region is $|.5-(1-x-.5)| = |1-1+x| = x$, and the total length is just $1-x$. So the probability our second cut is valid is $\frac{x}{1-x}$.</p>
<p>Putting it all together, we get the probability that our second cut is valid given a first cut at $x$ is $\frac{1-x}{1} \cdot \frac{x}{1-x} = x$. Kind of neat that the probability is exactly proportional to the length of the first break. But of course, $x$ isn&#39;t constant. It too is a random variable, so we can average it to get an expected probability across a large number of trials.</p>
<center>
$\frac{1}{\frac{1}{2} - 0} \int_0^{\frac{1}{2}} x \,dx = 2 \cdot \frac{x^2}{2} \Big]_0^{\frac{1}{2}} = (\frac{1}{2})^2 = \frac{1}{4}$
</center>

<p>As a gut check, this should make sense as .25 is exactly the midpoint between 0 and .5, the boundaries we set at the start of the solution. </p>
<hr>
<p>So, if you break a stick at 2 uniformly random points into 3 segments, the probability those 3 segments can form a triangle is exactly $\frac{1}{4}$.</p>
]]></description>
         <link>http://xperimex.github.io/blog/triangle-puzzle</link>
         <guid isPermaLink="true">http://xperimex.github.io/blog/triangle-puzzle</guid>
         <dc:creator><![CDATA[Adi Mittal]]></dc:creator>
      </item>
      <item>
         <title><![CDATA[Linear Programming and Laudable Polytopes]]></title>
         <description><![CDATA[Monopolize the world with mx+b 

 <p>You&#39;re a business tycoon. You have ideas in mind but no products on hand. You need to make a quick buck now and all you have is some needlework on your belt to carry you. If you wanted to maximize profit between making hats and shirts, what combination of the two should you make? Well, let&#39;s look at what our goal is. If I make \$15 per shirt, and \$10 per hat, we can have a simple goal of</p>
<center>
$\max(15s + 10h)$
</center>

<p>Obviously, we can&#39;t just make infinite of each wearable. We have some constraints between available cloth, printing, and effort. If you have 20 sheets of cloth, and each shirt requires $\frac{1}{2}$ of one and the hats only require $\frac{1}{5}$ of one. For printing, maybe you only have enough ink for 100 prints total. Finally, hats are hard to make, so you cap yourself at only making 70 and no more. We have a list of constraints which can be nicely added as a set of inequalities:</p>
<center>
$\max(15s + 10h)$ </br>
$\begin{align}
\frac{1}{2}s + \frac{1}{5}h &amp; \leq 35 \
\newline
s + h &amp; \leq 100 \
\newline
h &amp; \leq 70
\end{align}$
</center>

<p>This isn&#39;t an easy system to solve as, well, we&#39;re not solving anything in the traditional sense by plugging in equations to one another, nor is it a standard maximization problem where we can take some form of a gradient since every equation here is a line, so we would only get constants that give us no new information. </p>
<p>This type of problem where we want to maximize a linear equation that is also bound by a set of linear restraints is called a <strong>linear program</strong>. These types of problems are called specifically programs as you&#39;ll see that we have analytic ways to find solutions, but to find the <em>best</em> solution requires some well-crafted algorithms to make solving them faster and more efficient. Before we can understand the 2, and later the general $n$, variable set up, let&#39;s try an easier case.</p>
<h2 id="1d-linear-program">1D Linear Program</h2>
<p>As with all problems, let&#39;s try and cut back on degrees of freedom so we can really focus on what&#39;s going on here. Instead of maximizing a function of 2 variables, let&#39;s do a function of 1 variable.</p>
<center>
$\max(3x)$</br>
$\begin{align}
5x &amp; \leq 50 \
\newline
x &amp; \geq 6
\end{align}$
</center>

<p>This isn&#39;t all that interesting, as I&#39;m sure the answer is popping out almost immediately: $\max(3x)=30$ from since we can only have at most 10 of variable $x$ from the first constraint. What will become an important concept later is how we visualize these solutions to linear programs, so let&#39;s graph our inequalities on a number line to represent the quantity of variable $x$.</p>
<p><img src="/img/linear-program/1d-lp.png"></p>
<center style="color: #666;">
<p>Feasiblity region graphed for our 1-variable linear program.</p>
</center>

<p>In <span style="color:blue">blue</span>, we have our first constraint of showing all values of $x$ that satisfy $5x \leq 50$, and in <span style="color:red">red</span> we have our second constraint showing all $x$ that satisfy $x \geq 6$. Where those two regions overlap in the purple-ish area is the <strong>feasibility region</strong>, as well, it&#39;s the area where all of our constraints are satisfied and where <em>feasible</em> values of $x$ lie. The feasibility region defines a <em>polytope</em>, a generalization of the 2D polygon and 3D polyhedron. The key takeaway is that our solution of $x=10$ is an <em>edge case</em>: it lies on the furthest possible boundary of our feasibility region. </p>
<p>This makes sense for two reasons. 1) We want to always be looking to maximize or minimize our <strong>objective function</strong> ($3x$, in this case) so if we can add more or less of $x$ to our solution, we want to do that depending on our goal. This is a more intuitive way to show reason 2) our function is linear, so as long as we go in one direction, it will always be increasing or decreasing. Let&#39;s add the $y$-axis into this graph and let $y=3x$ to see the value of the function we&#39;re maximizing at different values of $x$.</p>
<p><img src="/img/linear-program/1d-lp-z.png"></p>
<center style="color: #666;">
<p>Objective function $y=3x$ plotted with an extra dimension.</p>
</center>

<p>Since our objective function is linear, it is directly proportional to $x$, so as $x$ increases or decreases, $y$ also has to only increase or decrease with no chance of weird curves or bends in its function. So if we want to maximize our function, we just want to walk in the direction of $x$ that does so until we hit the edge of our feasiblity region. Similarly, if we wanted to minimize it, we&#39;d walk the other way along $x$ that decreases $y$.</p>
<p>With this in mind, we can now go back to our original 2 variable case.</p>
<h2 id="2d-linear-program">2D Linear Program</h2>
<p>Recalling what our original setup was</p>
<center>
$\max(15s + 10h)$ </br>
$\begin{align}
\frac{1}{2}s + \frac{1}{5}h &amp; \leq 35 \
\newline
s + h &amp; \leq 100 \
\newline
h &amp; \leq 70
\end{align}$
</center>

<p>Let&#39;s plot our feasibility region like we did before. Only now, it&#39;ll be a 2-dimensional region instead of just the number line. We&#39;ll put $s$ for shirts on the $x$-axis and $h$ for hats on the $y$-axis.</p>
<p><img src="/img/linear-program/2d-lp.png"></p>
<center style="color: #666;">
<p>5 vertices map out our 2D linear program&#39;s feasibile region, meaning there are 5 possible points that can be our optimal solution.</p>
</center>

<p>Just as in the 1-variable case, our solution for maximizing our objective function should lie at the edge of our feasible region. I&#39;ve marked the feasible region&#39;s defining vertices in purple. It&#39;s worth pointing out that I have added an additional vertex not defined by our original constraints, and that&#39;s the vertex $(0,0)$. This is aptly called the non-negativity constraints as it, well, constrains our variables to be non-negative (shocking, right). These tend to be a requirement for some minimization cases just so that we don&#39;t end up with problem of running into a pair of negaively infinite numbers as our solution, which obviously doesn&#39;t make sense.</p>
<p>Although what I said about our solution being on the edge of the region isn&#39;t true, I can tell you more about our maximum solution: it will (usually) be one of the vertices of our feasible region. If you want a more math-based explanation, check <a href="https://cs.stackexchange.com/questions/84343/simplex-algorithm-why-must-the-optimal-value-of-the-lp-lie-on-the-face-or-verte">this</a> out, but there&#39;s a very intuitive way to view think of this, especially with a 2-variable linear program. </p>
<p>Remember how in the 1D case, our objective function $y=3x$ could be represent as a line? We can do a similar idea and add a third $z$-axis to our 2D problem and get $z=15s+10h$. This equation gives us a 3-dimensional plane as we encode the number of shirts, hats, and the amount of money they profit. Our constraints are also planes, acting as curtain-like walls extending forever vertically in the $z$-axis (as all values of $z$ will satisfy whatever values of $s$ and $h$ that lie on the line). Now, imagine our objective function plane of $z=15s+10h$ to be like a tilted table, and we place a ball on it to roll, what does the ball do? Well, the ball will just roll down the incline to the lowest point gravity will push it down. Normally, the ball will roll down forever and ever as our table extends infinitely in all directions, but we have our constraining walls to stop the ball. As soon as the ball hits a wall, it&#39;ll continue to slide down that wall as long as the ground tilts downward. It&#39;ll only stop if another wall pushes it into a corner, which is where our constraints form a vertex. Isn&#39;t that neat? The only times this won&#39;t be true is if one of our constraints form a wall that is exactly perpendicular to the direction the ball is rolling, in which case you will have a line segment worth of solutions (which includes two vertices at the end of it). This specific logic applies to finding minimums of our objective function, but you can also think of the reverse for maximums with a tilted ceiling and a balloon instead of a ball. It&#39;s basically a streamlined version of gradient descent since the gradient of the plane is always constant.</p>
<p>So if you manually check all 5 vertices, you&#39;ll find that a combination of $(50 \textrm{ shirts}, 50 \textrm{ hats})$ gives the optimal combination of $1250 profit. Not bad.</p>
<h2 id="the-simplex-algorithm">The Simplex Algorithm</h2>
<p>Not to dismiss the wonders of guess-and-check, but it only worked well for us due to the small number of variables and constraints we had. As we tackle more complex and intricate problems, we want to be able to solve linear programs much quicker and more efficiently. There are many algorithms that have been developed for LP optimization with varying motives, but the first one was George Dantzig&#39;s <strong>simplex algorithm</strong>.</p>
<p>The simplex algorithm is essentially a systematic way for us to narrow our guess-and-check quickly. We start at some vertex, and then travel edges of the feasbile region between vertices until it lands on the optimal solution. The idea is by turning our constraints into a matrix, we can use Gaussian elimination to move between possible candidate solutions until no improvement to our objective function can be made. Let&#39;s use our original 2-variable problem to try it out.</p>
<center>
$\max(15x + 10y)$ </br>
$\begin{align}
\frac{1}{2}x + \frac{1}{5}y &amp; \leq 35 \
\newline
x + y &amp; \leq 100 \
\newline
y &amp; \leq 70
\end{align}$
</center>

<p>To start, we&#39;re going to turn these inequalities into equations by adding <strong>slack variables</strong>. To avoid confusing variable names later, I have replaced $s$ with $x$ and $h$ with $y$. The idea is that if our inequalities are anything less than the right-hand side, we should be able to cover that excess by adding an extra variable to make it equal. Rewriting all of our inequalities (including the objective function with a new objective variable $z$) into equations, we get</p>
<center>
$\begin{align}
-15x - 10y + z &amp; = 0 \
\newline
\frac{1}{2}x + \frac{1}{5}y + s_1 &amp; = 35 \
\newline
x + y + s_2 &amp; = 100 \
\newline
y + s_3 &amp; = 70
\end{align}$
</center>

<p>This is a system of linear equations we can encode as an augmented matrix!</p>
<center>
$
\begin{array}{cccccc|c}
{\bf x} &amp; {\bf y} &amp; {\bf s_1} &amp; {\bf s_2} &amp; {\bf s_3} &amp; {\bf z} &amp; \textbf{constraints} \\ \hline
\frac{1}{2} &amp; \frac{1}{5} &amp; 1   &amp; 0   &amp; 0 &amp; 0   &amp; 35 \\
1 &amp; 1 &amp; 0   &amp; 1   &amp; 0 &amp; 0   &amp; 100 \\
0 &amp; 1 &amp; 0   &amp; 0   &amp; 1 &amp; 0   &amp; 70 \\ \hline
-15 &amp; -10   &amp; 0   &amp; 0 &amp; 0   &amp; 1 &amp; 0 \\
\end{array}
$
</center>

<p>Here are some things to identify in our <strong>simplex tableau</strong> above. The first row is more a convenience than anything, keeping track of which column corresponds to each variable. The second, third, and fourth rows all correspond to some constraint we have rewritten as equations with slack. The fifth and final row is our objective function which we are trying to maximize. So, by default, we assume we start at the point $(0,0)$ in our feasibility region. Yes, it is a vertex and therefore a candidate solution, but obviously it&#39;s not the maximum solution we want, giving us a whopping $z=0$. How do we find the next candidate point? Well we first want to identify which of our variables would increase $z$ the quickest. Well, notice that $x$ has a coefficient of $-15$ in the objective function final row, while $y$ has only a value of $-10$ (we call these numbers <strong>indicators</strong>). This means for every unit of $x$, we gain an additional \$15 contrasting an additional \$10 from a singular unit of $y$. Since $x$ increases $z$ faster than $y$ does, let&#39;s focus on column 1.</p>
<p>If we&#39;re going to increase $x$ to increase $z$, how do we know how much to increase it by? We can use our handy constraints to tell us exactly that. What we do is we take each value in the $x$ column and divide its associated row&#39;s constraint by that value. So, for the $x$ variable we have</p>
<center>
$\begin{align}
35 \div \frac{1}{2} &amp; = 70 \
\newline
100 \div 1 &amp; = 100 \
\newline
70 \div 0 &amp; = \textrm{undefined}
\end{align}$
</center>

<p>Now why is this helpful? These divisions tell us the maximum amount of $x$ we can have according to each constraint (as we assume $y$ can be 0). So, if $\frac{1}{2}x + \frac{1}{5}y \leq 35$, then $x$ can be at most 70 without breaking that constraint. Similarly, $x$ can be at most 100 for the second constraint, and there&#39;s no limit for $x$ on the third constraint since it doesn&#39;t impact that inequality. So, this tells us we should use the first row as our guiding row! This is because if we used the second row with a maximum of 100, we would be violating our first constraint that $x \leq 70$. So, we call $\frac{1}{2}$ our <strong>pivot</strong> as we use that value to shift our focus from one vertex solution to another. We use our pivot to do Gaussian elimination, and create 0s in that column&#39;s other rows to land us at a new vertex.</p>
<center>
$
\begin{array}{cccccc|c}
{\bf x} &amp; {\bf y} &amp; {\bf s_1} &amp; {\bf s_2} &amp; {\bf s_3} &amp; {\bf z} &amp; \textbf{constraints} \\ \hline
\color{red}{\frac{1}{2}} &amp; \frac{1}{5} &amp; 1   &amp; 0   &amp; 0 &amp; 0   &amp; 35 \\
1 &amp; 1 &amp; 0   &amp; 1   &amp; 0 &amp; 0   &amp; 100 \\
0 &amp; 1 &amp; 0   &amp; 0   &amp; 1 &amp; 0   &amp; 70 \\ \hline
-15 &amp; -10   &amp; 0   &amp; 0 &amp; 0   &amp; 1 &amp; 0 \\
\end{array}
$
<br />
$\downarrow$
<br />
$R_2 - 2R_1$
<br />
$R_3 - 0R_1$
<br />
$R_4 + 30R_1$
<br />
$\downarrow$
<br />
$
\begin{array}{cccccc|c}
{\bf x} &amp; {\bf y} &amp; {\bf s_1} &amp; {\bf s_2} &amp; {\bf s_3} &amp; {\bf z} &amp; \textbf{constraints} \\ \hline
\frac{1}{2} &amp; \frac{1}{5} &amp; 1   &amp; 0   &amp; 0 &amp; 0   &amp; 35 \\
0 &amp; \frac{3}{5} &amp; -2   &amp; 1   &amp; 0 &amp; 0   &amp; 30 \\
0 &amp; 1 &amp; 0   &amp; 0   &amp; 1 &amp; 0   &amp; 70 \\ \hline
0 &amp; -4   &amp; 30   &amp; 0 &amp; 0   &amp; 1 &amp; 1050 \\
\end{array}
$
</center>

<p>This new vertex we have arrived at is exactly the solution you get only focusing on achieving a maximum $x$ at the point $(70,0)$, which is in fact, the solution with the most units of $x$.</p>
<p><img src="/img/linear-program/2d-lp-simplex1.png"></p>
<center style="color: #666;">
<p>The first step in our simplex algorithm visualized as we walk the edge between $(0,0)$ to $(70,0)$. This first step is definitely a better solution than before, but how can we tell if it is the <i>best</i> one?</p>
</center>

<p>\$1050 is definitely much better than netting \$0, but how do we know if we can make more? Going back to our objective function in the last row of our tableau, there&#39;s a $-4$ in the $y$ column, and as before, should mean there&#39;s a potential to increase profit by adding some $y$ component to our solution. Before we do that though, notice how some of our constraints have changed. $R_2$ used to denote $x+y+s_2=100$, but now it shows $\frac{3}{5}y - 2s_1 + s_2 = 30$, or as an inequality, $\frac{3}{5}y \leq 30$. What caused our constraint to change? It has to do with the fact we added rows together. Let&#39;s analyze the two original constraints in question of $R_1$ and $R_2$.</p>
<center>
$\begin{align}
\frac{1}{2}x + \frac{1}{5}y &amp; \leq 35 \
\newline
x + y &amp; \leq 100 \
\end{align}$
</center>

<p>We can then treat these as a system of equations like we did with Guassian elimination, and perform the same operation as we did before with $R_2 - 2R_1$.</p>
<center>
$\color{blue}{x + y} - (\color{red}{x + \frac{2}{5}y}) \leq 100 - 70$
</center>

<p>The important part to notice is that we&#39;re subtracting <em>from</em> the blue region $\color{blue}{R_2}$ and expecting a <em>positive</em> result (since both $x$ and $y$ must be greater than 0). This can only happen for our feasible region where the blue area $\color{blue}{R_2}$ is strictly greater than the red area $\color{red}{R_1}$. This appears only when $\color{red}{R_1}$ is <em>contained</em> within $\color{blue}{R_2}$. The $y$-value we solved for of $\frac{3}{5}y \leq 30$ is that maximum $y$ value of which that holds true. Anything above $(50,50)$ and suddenly the blue region is contained by the red, but anything below is fair game. </p>
<p>Our constraints haven&#39;t actually changed, they actually narrowed in given new information of which boundaries we are at with our current candidate solutions. </p>
<p>With that justified, we can now move on to repeating our pivoting process like before. In our new tableau, the $y$ column has a value of $-4$ in the indicators, meaning we have a possibility to increase $z$ by changing increasing $y$. Going through our process all over again to find and use the pivot:</p>
<center>
$\begin{align}
35 \div \frac{1}{5} &amp; = 175 \
\newline
\color{red}{30 \div \frac{3}{5}} &amp; \color{red}{= 50} \
\newline
70 \div 1 &amp; = 70
\end{align}$
</center>

<p>With a new pivot found...</p>
<center>
$\begin{array}{cccccc|c}
{\bf x} &amp; {\bf y} &amp; {\bf s_1} &amp; {\bf s_2} &amp; {\bf s_3} &amp; {\bf z} &amp; \textbf{constraints} \\ \hline
\frac{1}{2} &amp; \frac{1}{5} &amp; 1   &amp; 0   &amp; 0 &amp; 0   &amp; 35 \\
0 &amp; \color{red}{\frac{3}{5}} &amp; -2   &amp; 1   &amp; 0 &amp; 0   &amp; 30 \\
0 &amp; 1 &amp; 0   &amp; 0   &amp; 1 &amp; 0   &amp; 70 \\ \hline
0 &amp; -4   &amp; 30   &amp; 0 &amp; 0   &amp; 1 &amp; 1050 \\
\end{array}
$
<br />
$\downarrow$
<br />
$3R_1 - R_2$
<br />
$3R_3 - 5R_2$
<br />
$3R_4 + 20R_2$
<br />
$\downarrow$
<br />
$
\begin{array}{cccccc|c}
{\bf x} &amp; {\bf y} &amp; {\bf s_1} &amp; {\bf s_2} &amp; {\bf s_3} &amp; {\bf z} &amp; \textbf{constraints} \\ \hline
\frac{3}{2} &amp; 0 &amp; 5   &amp; -1   &amp; 0 &amp; 0   &amp; 75 \\
0 &amp; \frac{3}{5} &amp; -2   &amp; 1   &amp; 0 &amp; 0   &amp; 30 \\
0 &amp; 0 &amp; 10   &amp; -5   &amp; 3 &amp; 0   &amp; 60 \\ \hline
0 &amp; 0   &amp; 50   &amp; 20 &amp; 0   &amp; 3 &amp; 3750 \\
\end{array}
$
</center>

<p>There are no more negative numbers in the objective function row&#39;s indicators, so this should be our optimal solution! This is because of the actual equation that row represents:</p>
<center>
$50s_1 + 20s_2 + 3z = 3750$
<br />
$3z = 3750 - 50s_1 - 20s_2$
</center>

<p>Since every variable, including our slack variables $s_1$ and $s_2$, is non-negative, the maximum our objective function can be is $3z=3750$ with both $s_1$ and $s_2$ equal to 0. So, while we may be done doing computing our solution, we should simplify our tableau to make it more readable. Let&#39;s make $x$, $y$, $z$, and $s_3$—our non-zero variables—have coefficients of 1 so we can easily find their values.</p>
<center>
$
\begin{array}{cccccc|c}
{\bf x} &amp; {\bf y} &amp; {\bf s_1} &amp; {\bf s_2} &amp; {\bf s_3} &amp; {\bf z} &amp; \textbf{constraints} \\ \hline
1 &amp; 0 &amp; \frac{10}{3}   &amp; \frac{-2}{3}   &amp; 0 &amp; 0   &amp; 50 \\
0 &amp; 1 &amp; \frac{-10}{3}   &amp; \frac{5}{3}   &amp; 0 &amp; 0   &amp; 50 \\
0 &amp; 0 &amp; \frac{10}{3}   &amp; \frac{-5}{3}   &amp; 1 &amp; 0   &amp; 20 \\ \hline
0 &amp; 0   &amp; \frac{50}{3}   &amp; \frac{20}{3} &amp; 0 &amp; 1   &amp; 1250 \\
\end{array}
$
</center>

<p>Our second step in the simplex algorithm brought us to our optimal solution of $x=50$, $y=50$, $s_1=0$, $s_2=0$, $s_3=20$, and $z=1250$.</p>
<p><img src="/img/linear-program/2d-lp-simplex2.png"></p>
<center style="color: #666;">
<p>The second and final step in the simplex algorithm takes us from our last candidate solution $(70,0)$ to the optimal vertex of $(50,50)$.</p>
</center>

<p>Here&#39;s a summary of the simplex algorithm to solve linear programs:</p>
<ol>
<li>Rewrite the objective function and constraints into equations with slack variables.</li>
<li>Create the initial simplex tableau using the newly written equations.</li>
<li>Identify the most negative indicator to find the pivot variable.</li>
<li>Calculate quotients to find upper bounds on the pivot variable, and select the smallest quotient; this is the pivot for this iteration.</li>
<li>Using Gaussian elimination and row operations to turn all other values in the column to 0 using the pivot.</li>
<li>If any negative indicators remain after all row operations, repeat steps 3–5.</li>
<li>If no negative indicators remain, we are done and at the optimal solution$^*$!</li>
</ol>
<p>While we only looked at 1- and 2-dimensional linear programs, remember that this can work for as many variables as you&#39;d like, which is nice since I don&#39;t want to deal with imagining a ball rolling down a 12-dimensional tabletop to find my function minimum. There is a small asterisk though, since sometimes the simplex algorithm can &quot;stall&quot; or &quot;cycle&quot;, resulting in no net improvements of the objective function. Fortunately <a href="https://en.wikipedia.org/wiki/Linear_programming#Algorithms">other algorithms</a> based on other concepts have been built to not just be quicker, but avoid degenerate cases stalling and cycling.</p>
<h2 id="sensitivity-and-slack-analysis">Sensitivity and Slack Analysis</h2>
<p>What the values of $x$, $y$, and $z$ should be clear as those correspond to the point on the feasible region and maximum of the function, but what do the values of $s_1$, $s_2$, and $s_3$ mean? Recall that these are our <strong>slack variables</strong> as these are the variables that turned our constraining inequalities into equations by accounting for any <em>slack</em> in the constraints themselves. So, if we have 0 slack for one of our constraints, it means that we are using up as much of that constraint as we can; there is no slack to account for, and the corresponding slack variable is 0. If there is slack, it means we are not using up a constraint to its fullest potential. Recall our third constraint was </p>
<center>
$y \leq 70 \rightarrow y + s_3 = 70$
</center>

<p>Also remember that our optimal solution included that $y=50$. We set a cap of $y=70$, but we are only using 50 of those possible 70 units. $s_3$ tells us that in the third constraint, we have an excess of 20 unused constraining units. In that same sense, $s_1$ and $s_2$ tell us we have 0 wasted resources for the first and second constraints. This also tells us that we are precisely at the vertex of where the first and second constraints graphically meet, since our solution is on the edge of both inequalities.</p>
<p>That&#39;s not the only information our slack variables tell us, though. You can also find how sensitive our result is in the final row of our tableau. The $\frac{50}{3}$ and $\frac{20}{3}$ tells us for every additional unit we add to constraints of $R_1$ or $R_2$, we will make an additional \$ $\frac{50}{3}$ or \$ $\frac{20}{3}$ respectively since $\frac{50}{3}(s_1 + 1) = \frac{50}{3}s_1 + \frac{50}{3}$. These are called <strong>shadow prices</strong> of our objective function. If you want to read more about shadow prices and other marginal analysis such as <strong>reduced costs</strong>, <a href="http://web.mit.edu/15.053/www/AMP-Chapter-03.pdf">MIT OpenCourseWare</a> has you covered, but for now there are a few cool extensions of linear programming I want to cover.</p>
<h2 id="duality-and-dual-problems">Duality and Dual Problems</h2>
<p>Even though we have a systematic way to find our ideal solution to a linear program, we could have quickly found some facts about our solution before we started. Again, here is our previous, 2-variable linear program.</p>
<center>
$\max(15x + 10y)$ </br>
$\begin{align}
\frac{1}{2}x + \frac{1}{5}y &amp; \leq 35 \
\newline
x + y &amp; \leq 100 \
\newline
y &amp; \leq 70
\end{align}$
</center>

<p>In our 1st constraint, we could have equivalently rewritten it as</p>
<center>
$30x + 12y \leq 2100$
</center>

<p>by multiplying both sides by 60. Furthermore, since both $x$ and $y$ are greater than 0, we can also compare it to our objective function.</p>
<center>
$15x + 10y \leq 30x + 12y \leq 2100$
</center>

<p>So we now have an upper bound on our objective function: we know for sure it has to be less than 2100. We can be even smarter about this and do a similar process with our second constraint. By multiplying both sides of the second constraint by 15, we can say</p>
<center>
$15x + 10y \leq 15x + 15y \leq 1500$
</center>

<p>which gives us an even tighter upper bound on our optimal solution. This is the heart of <strong>duality</strong>: instead of trying to directly solve our maximization problem, we can turn it into an equivalent minimization problem to find the lowest upper bound of our objective function, indirectly solving it.</p>
<p>We can generalize this by multiplying all of our constraints by a scalar $a_i$ for each constraint and adding them all together.</p>
<center>
$\begin{align}
\frac{1}{2}a_{1}x + \frac{1}{5}a_{1}y &amp; \leq 35a_1 \
\newline
a_{2}x + a_{2}y &amp; \leq 100a_2 \
\newline
a_{3}y &amp; \leq 70a_3
\end{align}$
</center>

<p>Adding these all together, we get a unifying inequality of</p>
<center>
$\color{red}{15x + 10y} \leq (\frac{1}{2}a_{1} + a_{2})x + (\frac{1}{5}a_{1} + a_{2} + a_{3})y \leq 35a_1 + 100a_2 + 70a_3$
</center>

<p>Lastly, remember this is supposed to be an upper bound on our objective function, so we set this all greater than our objective function which I&#39;ve highlighted in <span style="color:red">red</span>. In our first few tries to bound the problem, we had $(a_1, a_2, a_3)$ equal $(60,0,0)$ and $(0,15,0)$ respectively. We can summarize our goal of minimizing the right-hand side while maintaining all these inequalities as true as</p>
<center>
$\min(35a_1 + 100a_2 + 70a_3)$ </br>
$\begin{align}
\frac{1}{2}a_1 + a_{2} &amp; \geq 15 \
\newline
\frac{1}{5}a_1 + a_2 + a_3 &amp; \geq 10 \
\end{align}$
</center>

<p>This looks like another linear program! We originally started with a <strong>primal</strong> problem with 2 variables and 3 constraints and used it to formulate its <strong>dual</strong> problem with 3 variables and 2 constraints!</p>
<p>But, what even is the purpose of this dual formulation? We already have a way to solve for an optimal solution, why needlessly copmlicate it with an extra intermediary step? The dual problem is useful as it allows us to readily access a lot of the sensitivity analysis. Each variable $a_i$ we&#39;re solving in the dual problem corresponds to the optimal <em>shadow price</em> (marginal utility of a resource) of the $i^\textrm{th}$ constraint in the primal problem.</p>
<p>Let&#39;s take a quick look back at our primal problem&#39;s solution. Recall that it had shadow prices of \$ $\frac{50}{3}$ for the first constraint of $\frac{1}{2}x + \frac{1}{5}y \leq \color{blue}{35}$, a shadow price of \$ $\frac{20}{3}$ for the second constraint of $x + y \leq \color{blue}{100}$, and a final shadow price of $0$ for the third constraint of $y \leq \color{blue}{70}$. If we value our total resources (highlighted in <span style="color:blue">blue</span>) at their marginal costs, we get that</p>
<center>
$\color{blue}{35} \cdot \frac{50}{3} + \color{blue}{100} \cdot \frac{20}{3} + \color{blue}{70} \cdot 0 = 1250$
</center>

<p>which is precisely the optimal profit we got originally from the primal problem. The leading principle of a dual problem is that if we can solve for the optimal marginal profits of each resource, then we know implicitly how much of that item we should buy given the total selling price of each primal variable.</p>
<center>
$\begin{array}{c|c}
\min(35a_1 + 100a_2 + 70a_3) &amp; \textrm{Minimize total cost of resources} \\
\newline
\frac{1}{2}a_1 + a_{2} \geq 15 &amp; \textrm{Marginal profit for variable $x$ must be at least 15} \\
\newline
\frac{1}{5}a_1 + a_2 + a_3 \geq 10 &amp; \textrm{Marginal profit for variable $y$ must be at least 10} \\
\end{array}$
</center>

<p>We try to minimize the cost of our primal constraints, while trying to ensure our dual constraints satisfy the coefficients of the primal objective function. In the case of shirt and hat selling, we want our marginal profits to at least equal the price we want to sell our products at. Even more interestingly, just like how our dual variables are equal to the primal shadow prices, the dual shadow prices are equal to the primal variables! Everything has been switched around!</p>
<p>Curiosities aside, we still haven&#39;t talked about many of the reasons <em>why</em> analyzing dual problems is useful. Here&#39;s a rundown of some of the benefits of duality:</p>
<ol>
<li><strong>Sometimes it&#39;s just easier:</strong> As you just saw, we turned a problem of 2 variables and 3 constraints into one of 3 variables and 2 constraints, and turned it from a question of maximization to one of minimization. For problems with few variables and lots of constraints, it&#39;s usually much easier to turn it into a problem with lots of variables and fewer constraints as every constraint in the problem will add some number of extra vertices for algorithms like the simplex to check, making it less efficient to check every case. </li>
<li><strong>Feasibility and boundedness:</strong> Sometimes a linear program will have no solutions whatsoever to check (imagine constraints like $x \geq 0$ and $x \leq 0$; can&#39;t be both at the same time). If the primal is unbounded (think no non-negativity constraints), then the dual is infeasible, and vice versa. </li>
<li><strong>Specialized algorithms and theorems:</strong> Beyond optimizing business plans, duality has found its way into <a href="https://brilliant.org/wiki/hungarian-matching/">combinatorics</a>, <a href="https://en.wikipedia.org/wiki/Max-flow_min-cut_theorem">graph theory</a>, and even into the fame of game theory as a means to prove the <a href="https://theory.stanford.edu/~tim/w16/l/l10.pdf">minimax theorem for zero-sum games</a>. Many more results like these tend to stem out of the <a href="https://sites.math.washington.edu/~burke/crs/407/notes/section4.pdf">Weak and Strong Duality Theorems</a> (Weak Duality talks about how a dual problem can set an upper bound to a primal soultion, and Strong Duality says it can <em>find</em> the optimal primal solution).</li>
</ol>
<hr>
<p>Duality is a powerful concept not just in linear programming, but frequently pops up in <a href="https://mathworld.wolfram.com/DualGraph.html">other areas of math</a> and recognizing when you can represent one problem with another is a great tool to have in your back pocket.</p>
<h2 id="conclusion">Conclusion</h2>
<p>Linear programming is only one small niche of optimization study, but the depth and applicability in its simple premises is wildly effective. Starting out in the 40s with Dantzig&#39;s original simplex algorith, it has grown to affect much of computer science and math to systematically solve otherwise impossibly long computations. Even now, variations of the original linear programming formulation is still being researched with new methods to not only solve them, but also adding new fundamental restrictions to the problem. If you were a car manufacturer that wanted to know the optimal distribution of models to produce, you can&#39;t just make 41237.7963 cars; you would only care about integer solutions, and thus <strong>integer linear programming (ILP)</strong> was born. Linear programming&#39;s innate utility in optimization has lent itself kindly to modern applications, but from ILP, to the even crazier <strong>mixed-integer linear programming</strong> with a combination of integer and non-integer variables, as well as duality, LP has found itself touching every corner of math from combinatorics to graph theory as a simple multidimensional geometric encoding of a constraint function.</p>
]]></description>
         <link>http://xperimex.github.io/blog/linear-programming</link>
         <guid isPermaLink="true">http://xperimex.github.io/blog/linear-programming</guid>
         <dc:creator><![CDATA[Adi Mittal]]></dc:creator>
      </item>
      <item>
         <title><![CDATA[Billiard Balls and Secure Squares]]></title>
         <description><![CDATA[The ultimate secret to win at pool and laser tag 

 <script src="//cdn.jsdelivr.net/npm/p5@1.4.0/lib/p5.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/g9/1.0.16/g9.js'></script>

<p>Today&#39;s post is one that&#39;s been months in the making. It originally started as one that only covers a single problem, but quickly branched off as I delved deep into dozens of papers and videos, just with more and more questions coming up. We&#39;re going to be discussing one of the oldest mixed studies of algebra and geometry: <em>dynamical systems</em>. Today&#39;s post is going to be a long one, but should have a fair number of fun visuals to keep it worth the scroll. This is really two, maybe three posts in one, so I recommend reading this with breaks at each header as to make it less overwhelming. </p>
<p>To begin, let&#39;s look at a type of problem you might have <em>experienced</em> before, rather than have read formally: <strong>billiard problems</strong>.</p>
<!-- [INSERT TABLE OF CONTENTS LATER WHEN DONE: 1) MATH >> SPLIT DYNAMICAL SYSTEMS WITH ALHAZEN'S AND ILLUMINATION PROBLEMS AND OTHERS THEN SECURE POLYGON 2) GRAPHICS >> TALK ABOUT HOW USEFUL VECTORS ARE, SHOW WHY CURRENT INTERSECTION ALGORITHM CHEATS AND INTRO TO RAYTRACING]

look into if hexagon/triangle/other polygons that can or can't tile the plane are secure polygons like the square -->
<p><span style="color: #666;"><i>For the best experience, avoid reading this in Safari; most other browsers should work and load the visuals correctly, but Safari breaks rendering a few of them.</i></span></p>
<h2 id="ricochets-and-rebounds">Ricochets and Rebounds</h2>
<p>If you have ever played pool, or even laser tag, you might already be familiar with <em>billiard problems</em>. If you have a billiard ball you want to land in a pocket, but there are other balls in your way, where on the side of the pool table do you want to bounce your ball to land in the pocket? Alternatively, if you have a laser gun and an opponent by a mirror, where do you want to aim your laser to hit your opponent? To reduce this problem further (and for future reference), if you have a <span style="color:red">laser</span>, a <span style="color:green">target</span>, and a wall, where do you want to aim the laser to hit the target?</p>
<center>
<div id="billiardIntro"></div>
</center>
<center style="color: #666;">
<p>Can you make the <span style="color:red">light</span> hit the <span style="color:green">target</span>? The light automatically follows your cursor, but you can press the <i>1</i> key on your keyboard to lock the angle. Try dragging the points for different problem setups.</p>
</center>

<p>We covered how to solve this exact problem in a <a href="https://xperimex.com/blog/retroreflectors/#fermat-s-principle">previous post</a>, which also shows how light reflects and bounces (which is what we&#39;ll be using today). To recap that post:</p>
<ul>
<li>Our laser/billiards bounces must follow the <strong>Law of Reflection</strong>: the angle the laser strikes the mirror is the same angle it reflects.</li>
<li>To solve for where to bounce the light off the wall, we create a &quot;mirror world&quot; to find the reflection point.</li>
</ul>
<p>The idea is to reflect our target over the wall, draw a straight line from our laser to the reflected target, and the intersection point is the point of reflection. This seems arbitrary, but there&#39;s a good reason for it: the angle that our straight line creates in the &quot;mirror world&quot; is equal to the incident angle, and therefore ensures the angle the light bounces off at in the normal world is equal. I recommend following through with the previous post for a more on this, but the following demonstration should suffice.</p>
<center>
<div id="billiardSolved"></div>
</center>
<center style="color: #666;">
<p>We reflect our <span style="color:green">target</span> over the wall, and draw a line between the <span style="color:red">light</span> and that reflection. Can you see why this finds us our desired reflection point?</p>
</center>

<p>Simple enough, but this reflection technique is an invaluable tool for solving these types of problems, so put a pin in that for later. But now, let&#39;s look at a problem that throws that very easy technique out of the window.</p>
<h2 id="alhazen-s-circular-mirror">Alhazen&#39;s Circular Mirror</h2>
<p>Dynamical systems have been studied since forever at this point. One of the oldest (hard) billiard problems comes from Ptolemy 150 AD:</p>
<p><strong>If you have a candle and a circular mirror, where on the wall do you have to aim to hit a target?</strong></p>
<p>This problem plagued the Greeks for centuries, primarily since they tried to solve this with their typical ruler-and-compass constructions. Dr. Peter Neumann <a href="https://www.tandfonline.com/doi/abs/10.1080/00029890.1998.12004920">proved that this is an impossible task</a>, but other solutions and proofs have arisen over the years by some of the most famous mathematicians including Huygens and l&#39;Hôpital. The problem was named after Abu Ali al Hassan ibn al Hassan ibn Alhaitham, later retroactively given the mononym Alhazen, who discussed this in book <em>Optics</em> around the 10th century.</p>
<center>
<div id="alhazenIntro"></div>
</center>
<center style="color: #666;">
<p>Now, with the same <span style="color:red">light</span> and <span style="color:green">target</span>, can you hit the target? Drag and drop points for different problem setups; if you want to lock the light&#39;s direction, hit the <i>2</i> key.</p>
</center>

<p>First, let&#39;s clear some details up.</p>
<ul>
<li>To make sense of a curved mirror, the reflection acts according to the <em>tangent</em> line at the point of reflection. So, you can think of the curved mirror as made up of infinite, infinitesimal straight-walled mirrors.</li>
<li>The <span style="color:red">light</span> is a pure <strong>ray</strong> like a laser. No point source or beams to get cheap answers like, &quot;If I stand <em>about</em> here, some of the light will reflect on the target.&quot; This is a laser beam that can only blind us if it directly hits us.</li>
<li>In a similar manner to the <span style="color:red">light</span> assumption, the <span style="color:green">target</span> has been reduced a to 0-dimensional <strong>point</strong>. The <span style="color:red">light</span> must hit the <span style="color:green">target</span> <em>exactly</em> in our solution.</li>
<li>And, importantly, we assume a solution exists. If the light and target are on opposite sides of the circle, clearly no reflection will make it. So, to simplify, we&#39;ll just assume that they are in positions with a possible reflection point.</li>
</ul>
<p>Before I show you my solution to the problem, I suggest you try this problem for yourself. This is one of the few, very simple-to-state problems that has caused me a lot of trouble deciphering a clean solution for it. Mathematicians have developed quite the dictionary to solve this one problem <!-- talk about circle inversion, algebraic, and ellipse solutions --> which we&#39;ll discuss a bit at the end, but only one way has appeared the most elegant (in the most stretched definition) to me.</p>
<h3 id="clutch-complex-contours">Clutch Complex Contours</h3>
<p>The way I solved this problem was with the magnificence of complex numbers. Let&#39;s center our circular mirror as the unit circle $Ø$ at the origin $O$, and let&#39;s call the light and target $\color{red}{a}$ and $\color{green}{b}$ (if your circular mirror is not of radius 1, just scale all coordinates appropriately to make it so). We want to solve for the point $\color{purple}{z}$ on the mirror such that $\angle azO = \angle Ozb$. </p>
<p>The path our light takes can be modelled in two segments: from the candle $a$ to the mirror $z$ as $a-z$, and then from the mirror to the target as $b-z$ (you&#39;ll see why we pick these directions later). To make our lives easier, let&#39;s rotate our whole setup so that the mirror reflection point occurs at $z=1+0i$ by dividing our whole setup by $z$. So right now, we have two vectors representing our reflected ray of light as $\frac{a-z}{z}$ and $\frac{b-z}{z}$ (if you&#39;re not completely familiar with the geometry of complex numbers and why this division tactic works, here&#39;s a good <a href="https://www.youtube.com/watch?v=5PcpBw5Hbwo">introductory video</a>). </p>
<p><img src="/img/secure-squares/alhazenDivide.png"></p>
<center style="color: #666;">
<p>Here we have the <span style="color:red">light</span> at $\color{red}{a}$ and the <span style="color:green">target</span> at $\color{green}{b}$ at some arbitrary spots, with a theoretical <span style="color:purple">solution</span> at $\color{purple}{z}$. Since we don&#39;t want to work with some random tilted axis, we divide everything by $\color{purple}{z}$ to so that our set up is centered around the real axis with $\color{purple}{z} = 1$. </p>
</center>

<p>Since our vectors are now symmetrical about the real axis, we know that $\arg(\frac{a-z}{z}) = -\arg(\frac{b-z}{z})$ as the angle of reflection must be equal angle to the angle of incidence (see this <a href="http://xperimex.com/blog/retroreflectors/">previous post</a> for a proof).</p>
<p>Ok, so why is any of this helpful? Just as we divided by two complex numbers to subtract the angles of their vectors, we can multiply them to add them together. If we multiply $(\frac{a-z}{z})(\frac{b-z}{z})$, we get that their angles sum to 0 since their arguments are opposite! If the argument of the product is 0, that means that it lies on the real axis, and therefore is a real number! We can then extract that</p>
<center>
$\large{(\frac{a-z}{z})(\frac{b-z}{z}) \in \mathbb{R} \rightarrow \operatorname{Im}((\frac{a-z}{z})(\frac{b-z}{z})) = 0}$
</center>

<p>where $\operatorname{Im}(c)$ denotes the imaginary part of a complex number $c$. Noting that $\color{purple}{z} \cdot \overline{\color{purple}{z}} = 1$ we can further simplify this equation.</p>
<center>
$\begin{align}
\operatorname{Im}((\frac{a-z}{z})(\frac{b-z}{z})) &amp; = 0 \
\newline
\operatorname{Im}(\frac{ab - (a+b)z + z^2}{z^2} \cdot \frac{\overline{z}^2}{\overline{z}^2}) &amp; = 0 \
\newline
\operatorname{Im}((ab)\overline{z}^2 - (a+b)\overline{z} + 1) &amp; = 0 \
\newline
\operatorname{Im}((ab)\overline{z}^2) - \operatorname{Im}((a+b)\overline{z}) + \operatorname{Im}(1) &amp; = 0
\end{align}$

<br>
<br>

$\large{\operatorname{Im}((ab)\overline{z}^2) = \operatorname{Im}((a+b)\overline{z})}$
</center>

<p>This might not seem like much, this describes all possible points $\color{purple}{z}$ our reflection point can lie on! Let $\color{purple}{z} = x + yi$, $\color{red}{a} \color{green}{b} = p + qi$, and $\color{red}{a} + \color{green}{b} = r + si$, and we can rewrite our equation in terms of cartesian coordinates $(x,y)$.</p>
<center>
$\begin{align}
\operatorname{Im}((ab)\overline{z}^2) &amp; = \operatorname{Im}((a+b)\overline{z}) \
\newline
\operatorname{Im}((p+qi)(x-yi)^2) &amp; = \operatorname{Im}((r+si)(x-yi)) \
\newline
\operatorname{Im}(px^2 \color{red}{-2pxyi}-py^2 + \color{red}{qx^2i} + 2qxy \color{red}{- qy^2i}) &amp; = \operatorname{Im}(rx \color{red}{-ryi} + \color{red}{sxi} + sy) \
\end{align}$

<br>
<br>

$\large{q(x^2 - y^2) - 2pxy = sx - ry}$
</center>

<p>This is an equation for a hyperbola! And since we want $\color{purple}{z}$ to lie on the circumference of our spherical mirror, the point $(x,y)$ must also be a solution to $x^2+y^2 = 1$ to lie on the unit circle as well. To find where our desired $\color{purple}{z}$ is, we just need to find the intersection between this hyperbola and the unit circle.</p>
<p><img src="/img/secure-squares/alhazenHyperbola.png"></p>
<center style="color: #666;">
<p>Given our previous <span style="color:red">light</span> and <span style="color:green">target</span> positions, we get this specific <span style="color:purple">hyperbola</span> which intersects our mirror in 4 locations, giving 4 possible reflection points. How can we compute their coordinates, and find the correct point?</p>
</center>

<center>
$
\begin{cases} 
q(x^2 - y^2) - 2pxy = sx - ry \ 
\newline
x^2 + y^2 = 1 
\end{cases}
$
</center>

<p>It&#39;s no coincidence that this problem involves finding the intersection between a circle and a hyperbola. While yes, all of our complex number algebra does the job, there&#39;s a <a href="https://forumgeom.fau.edu/FG2012volume12/FG201216.pdf">purely geometrical</a> way of coming to the same conclusion involving isogonal conjugates. I wasn&#39;t very familiar with them, so I decided to present the complex number approach instead.</p>
<p>You could try and solve this system of equations, but the nature of the conic sections make it a pretty tedious and gross task. Fortunately, we can actually reduce this sytem of 2 simultaneous equations to a single polynomial! Going back to one of our previous equations:</p>
<center>
$\operatorname{Im}((ab)\overline{z}^2 - (a+b)\overline{z} + 1) = \operatorname{Im}((ab)\overline{z}^2 - (a+b)\overline{z})  = 0$
</center>

<p>The important thing to note is that we have a complex number whose imaginary component is equal to 0. This means that this expression is equal to its conjugate, since there is no imaginary component to flip the sign of: $x + 0i = x - 0i = x$.</p>
<center>
$\begin{align}
(ab)\overline{z}^2 - (a+b)\overline{z} &amp; = \overline{(ab)\overline{z}^2 - (a+b)\overline{z}} \
\newline
(ab)\overline{z}^2 - (a+b)\overline{z} &amp; = (\overline{ab})z^2 - (\overline{a+b})z 
\end{align}$
</center>

<p>Again noting that $\color{purple}{z} \cdot \overline{\color{purple}{z}} = 1$, we can multiply both sides by $\color{purple}{z}^2$ to get that</p>
<center>
$\large{(\overline{ab})z^4 - (\overline{a+b})z^3 + (a+b)z - ab = 0}$
</center>

<p>All we need are the complex solutions $\color{purple}{z}$, and since this a quartic equation, we <em>technically</em> have a <a href="https://en.wikipedia.org/wiki/Quartic_function#General_formula_for_roots">closed form solution</a>. Once we have the coordinates of our reflection points, all we do is graph $(\operatorname{Re}(\color{purple}{z}), \operatorname{Im}(\color{purple}{z}))$, and we are done.</p>
<p><img src="/img/secure-squares/alhazenPoly.png"></p>
<center style="color: #666;">
<p>Our complex quartic generates 4 possible solutions for $\color{purple}{z}$, all on the unit circle.</p>
</center>

<p>If these points look familiar, they should: they are precisely the points our hyperbola predicted before!</p>
<p><img src="/img/secure-squares/alhazenPolyHyper.png"></p>
<center style="color: #666;">
<p>While not ideal to compute, our hyperbola did in fact find the same potential solutions.</p>
</center>

<p>Also, notice how we only used information about where the supposed <span style="color:purple">solution</span> $\color{purple}{z}$ to find our quartic; we never specified any conditions for where the <span style="color:red">light</span> $\color{red}{a}$ or <span style="color:green">target</span> $\color{green}{b}$ had to be! This means we can have our <span style="color:red">light</span> and <span style="color:green">target</span> on the <em>inside</em> of our circular mirror and find points that satisfy the Law of Reflection.</p>
<p><img src="/img/secure-squares/alhazenInside2.png"></p>
<center style="color: #666;">
<p>A valid bounce inside a circular mirror.</p>
</center>

<p>The best part is, all 4 of the possible solutions our quartic and hyperbola find are valid! No need to worry about the laser clipping through the mirror randomly; it all works out. </p>
<hr>
<p>While we solved the problem, there are a few details to address that are not completely obvious about this approach using complex numbers.</p>
<h3 id="the-core-4">The Core 4</h3>
<p>Why are there 4 &quot;<span style="color:purple">solutions</span>&quot; according to our polynomial? Being a quartic equation, 4 complex solutions isn&#39;t unexpected, but they don&#39;t seem to have any physical significance for our bouncing laser. Obviously, only one looks like it can reflect our points correctly; how can <em>this</em> be considered a viable spot to aim your laser?</p>
<p><img src="/img/secure-squares/alhazenWrong.png"></p>
<center style="color: #666;">
<p>A supposed &quot;solution&quot; our quartic generates, despite the fact the laser has to phase through the mirror on its way to the target.</p>
</center>

<p>No mirror bounces like that, let alone allow the laser to move straight through it. Moreover, our Law of Reflection looks completely broken, too. What&#39;s happening here? </p>
<p>It lies in the direction of our vectors. Watch what happens as I extend the line segment from the <span style="color:green">target</span> to the &quot;<span style="color:purple">solution</span>&quot;.</p>
<p><img src="/img/secure-squares/alhazenWrongExt.png"></p>
<center style="color: #666;">
<p>If we extend the ray from the  <span style="color:green">target</span> to the &quot;<span style="color:purple">solution</span>&quot;, we can get a <span style="color: rgb(0,50,0)">&quot;mirrored target&quot;</span>, kind of like what we did for the straight wall case.</p>
</center>

<p>If we extend the ray, then it&#39;s clear that the Law of Reflection is satisfied, and this is true for the 3 other supposed &quot;<span style="color:purple">solutions</span>&quot;: every &quot;bad&quot; reflection point is correct if the rays are extended far enough. So the 4 &quot;<span style="color:purple">solutions</span>&quot; correspond with how are vectors are lined up, since if we change the direction of our light bouncing we can get different points where the Law of Reflection is satisfied.</p>
<p>That doesn&#39;t answer, though, how we know which point to pick as the &quot;correct&quot; reflection point? If you read the previous post on <a href="http://xperimex.com/blog/retroreflectors/">retroreflectors</a>, then you know light takes the fastest and (<a href="https://en.wikipedia.org/wiki/Brachistochrone_curve">only in this case</a>) shortest path. So, we just pick the point where the total distance of the light&#39;s path is minimized: $\min(|\color{purple}{z} - \color{red}{a}| + |\color{purple}{z} - \color{green}{b}|)$</p>
<h3 id="to-be-on-the-circle-or-not-to-be-on-the-circle-">To be (on the circle), or not to be (on the circle)</h3>
<p>Some of you might be wondering why this should produce <em>any</em> solutions on the unit circle—let alone 4 at that. That is in part by the property we have mentioned a few times: $\color{purple}{z} \cdot \overline{\color{purple}{z}} = 1$. If the geometry of this isn&#39;t obvious to you with the rotations and scalings, we can turn this into Cartesian coordinates by setting $\color{purple}{z}=x+yi$, we get that</p>
<center>
$\begin{align}
z \cdot \overline{z} &amp; = 1 \
\newline
(x+yi) \cdot (x-yi) &amp; = 1 \
\newline
x^2 - xyi + xyi + y^2 &amp; = 1 \
\end{align}$

<br>
<br>

$\large{x^2 + y^2 = 1}$
</center>

<p>Which is precisely the equation for the unit circle. The property that $\color{purple}{z} \cdot \overline{\color{purple}{z}} = 1$ forces $z$ to be on the unit circle.</p>
<p>…for the most part. The proof I&#39;ve highlighted is adapted from <a href="https://link.springer.com/article/10.1007/s40315-018-0257-z">this paper</a>. As it shows, if you have the  <span style="color:red">light</span> at $\color{red}{a}=.5+.5i$ and a <span style="color:green">target</span> at $\color{green}{b}=.5+0i$, two of the supposed solutions for $\color{purple}{z}$ are completely off the unit circle. </p>
<p><img src="/img/secure-squares/alhazenBreak.png"></p>
<center style="color: #666;">
<p>When $\color{red}{a}=.5+.5i$ and $\color{green}{b}=.5+0i$, one supposed reflection point is on the inside of the circle, and the other is so far outside of the circle its offscreen.</p>
</center>

<p>I&#39;m not totally sure why this happens, but the previously linked <a href="https://link.springer.com/article/10.1007/s40315-018-0257-z">paper</a> proves that at least two of the generated <span style="color:purple">solutions</span> must be on the unit circle.</p>
<hr>
<p>If you want to look at this problem more, there is also an <a href="https://www.jstor.org/stable/27968003">algebraic solution</a>, here there are ideas involving <a href="https://www.youtube.com/watch?v=4KHCuXN2F3I">tangent ellipses</a> in this <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.48.4794&amp;rep=rep1&amp;type=pdf">paper</a>, and there&#39;s even an approach discussed in Dorrie&#39;s <a href="http://mylibrary.website/books/100_Great_Problems_of_Elementary_Mathematics_Heinrich_Dorrie_Dover_2_Math.pdf"><em>100 Great Problems of Elementary Mathematics</em></a>. These would be my recommended starting points. For even more depth, this is a solution involving <a href="http://www.math.sjsu.edu/~alperin/Alhazen.pdf">origami</a> (yes, the paper folding) and here&#39;s the <a href="https://www.semanticscholar.org/paper/Alhazen%E2%80%99s-hyperbolic-billiard-problem-Poirier-Mcdaniel/e03af90f6ed37f42d0ed4edc836dd1173e69e5eb">same problem in hyperbolic space</a>.</p>
<!-- **INSERT SOMEWHERE INTERACTIVE JAVASCRIPT ALHAZEN SOLVER** -->
<hr>
<p>Now that we&#39;ve seen where billiard problems started, let&#39;s see how far they&#39;ve come with the main focus of today&#39;s post.</p>
<h2 id="get-down-mr-president-">Get Down Mr. President!</h2>
<p>You and an assassin are trapped in a square room. With a single bullet, the assassin wants to do everything he can to take you out without wasting his shot. You, however, came prepared and hired a bodyguard to prevent direct line of sight between you and the assassin. But remember, you&#39;re trapped in a room. Without hesitation, the assassin flicks a shot to the side and ricochets off the wall and grazes your arm, avoiding the bodyguard completely. You might have been lucky this time, but who knows what happens next.</p>
<p><strong>If you (<span style="color:green">target</span>) and an <span style="color:red">assassin</span> are placed in a square room, can you hire a finite number of <span style="color:blue">bodyguards</span> to prevent any shot from hitting you (including ricochets)?</strong></p>
<p>At first glance, this might seem absurd. There are an infinite number of ways for the assassin to line up and bounce his shot, so how can anything less than an infinite number of bodyguards suffice? As one might anticipate, this wouldn&#39;t be a blog post if it didn&#39;t have an incredible answer. </p>
<center>
<div id="secureSquareIntro"></div>
</center>
<center style="color: #666;">
<p>Can you hit the <span style="color:green">target</span> with the <span style="color:red">assassin</span>&#39;s shot despite the <span style="color:blue">bodyguards</span>? Drag the <span style="color:red">assassin</span> and <span style="color:green">target</span> points to move them, and press the <i>3</i> key to lock the angle.</p>
</center>

<p>It&#39;s no coincidence I placed the <span style="color:blue">bodyguards</span> where I did in the above widget; not only does a finite number of bodyguards make do, you can prove you only need to hire <strong>16</strong> to ensure 100% protection!</p>
<p>I first found this problem through <a href="https://youtu.be/a7gp9c2p0UQ">Tai-Danae Bradley&#39;s video</a> and <a href="https://www.math3ma.com/blog/is-the-square-a-secure-polygon">post</a>, where she writes up the proof very well on her own. It was this problem that inspired me to look for other problems to extend this post, and moreover it was a fun <a href="">programming challenge</a>. Here, I want to outline the proof with the key insights Bradley utilizes, as well as pose a few other questions of my own.</p>
<p>Just as we did before, let&#39;s clarify some problem details:</p>
<ul>
<li>Just like before, the <span style="color:red">assassin</span>&#39;s bullet is a pure <strong>ray</strong>, and the <span style="color:green">target</span> has been reduced a to 0-dimensional <strong>point</strong>.</li>
<li>Now, though, we have <span style="color:blue">bodyguards</span>, which are 0-dimensional points as well; if they are going to protect the <span style="color:green">target</span>, they have to fully take the hit.</li>
<li>Lastly, just to make it clear, this is a perfectly square room and the bullet ricochets at exact angles off the walls, so the <span style="color:red">assassin</span>&#39;s shot can bounce forever if needed to hit its mark.</li>
</ul>
<h3 id="the-tiling-torus">The Tiling Torus</h3>
<p>Let&#39;s look at an easy case: what if the assassin can only reflect off the left wall? Since this is a square room with straight walls, we can use our reflection trick from before. Now, though, we have to analyze the <span style="color:green">target</span>&#39;s position in space <em>relative</em> to the room. </p>
<center>
<div id="roomOneWall"></div>
</center>
<center style="color: #666;">
<p>By reflecting the room, we create a &quot;mirrored world&quot; to track our reflection.</p>
</center>

<p>I&#39;ve color-coded the left, right, top, and bottom walls to be <span style="color:rgb(255,200,0)">yellow</span>, <span style="color:gray">gray</span>, <span style="color:magenta">magenta</span>, and <span style="color:cyan">cyan</span> respectively. The reason if we want to track the <span style="color:green">target</span>&#39;s location within the room even after the reflection, we have to reflect the room itself too, creating an actual &quot;mirror world&quot; that I referred to earlier.</p>
<p>Ok, so that isn&#39;t too different than what we&#39;ve already been doing, so what&#39;s the point? The magic lies in modelling <em>multiple</em> bounces. Remember, we reflected over the <span style="color:rgb(255,200,0)">yellow</span> wall to say we wanted our bounce to be off that wall, but we can chain these reflections to give multiple instructions to our bounces. If we first reflect over the <span style="color:rgb(255,200,0)">yellow</span> wall and <em>then</em> the <span style="color:magenta">magenta</span> wall, we create a doubly mirrored world with our straight line showing the path of what 2 bounces looks like. </p>
<center>
<div id="roomTwoWall"></div>
</center>
<center style="color: #666;">
<p>Reflecting over a second wall gives us another straight-line intersection to find our first and therefore second reflection point too.</p>
</center>

<p>If you want to convince yourself this trick works for multiple bounces, I recommend finding the congruent angles within the mirrored world&#39;s straight line and the actual bounces within the room in question.</p>
<p>An important part of finding this mirrored world&#39;s straight line though is the fact that it intersects the colored walls in the order the <span style="color:red">assassin</span>&#39;s bullet bounces. In the initial setup provided, the straight line hits the <span style="color:rgb(255,200,0)">yellow</span> wall first before intersecting the <span style="color:magenta">magenta</span> wall, just as the beam&#39;s bounce path reflects off the <span style="color:rgb(255,200,0)">yellow</span> then <span style="color:magenta">magenta</span> walls <em>in that order</em>. If you move the <span style="color:red">assassin</span> and <span style="color:green">target</span>, you can see this idea holds for a <span style="color:magenta">magenta</span> then <span style="color:rgb(255,200,0)">yellow</span> wall bounce too.</p>
<p>So, if we wanted to model the <span style="color:red">assassin</span>&#39;s hitting the <span style="color:green">target</span> in more bounces, we just reflect our room more times and draw the straight line between the <span style="color:red">assassin</span> and <span style="color: rgb(0,50,0)">mirrored target</span>.</p>
<center>
<div id="roomSevenWall"></div>
</center>
<center style="color: #666;">
<p>Even with many more reflections of the room, our bullet still bounces off the colored walls in the order our straight line intersects them. Try dragging both the <span style="color:red">assassin</span>, <span style="color:green">target</span>, and <span style="color: rgb(0,50,0)">mirrored target</span> to see how the paths change. Note these are only paths that result in the <span style="color:red">assassin</span> successfully hitting the <span style="color:green">target</span>.</p>
</center>

<p>Moreover, since squares can tile the plane maintain the same &quot;silhouette&quot; under reflection, we can infinitely tile the plane with reflected copies of our room. Since a line through this plane can represent any bounce shot from the assassin in the original room, we have successfully simplified our problem setup. Why? With straight lines, we can now use coordinate geometry to place our bodyguards and not worry about annoying reflectedl light patterns within our square.</p>
<p>In more math-y terms, we have turned our original room into what is known as a <strong>flat torus</strong> (yes, the thing that&#39;s equal to a coffee cup). Essentially, all this means is that our problem sort of exists in a world similar to the game of <em>Asteroids</em>: as you exit the top or left of one flat torus, you enter through the bottom or right of another one (and vice versa). This fact is what allows us to tile the plane consistently with our problem setup. If you look back at the 2-by-2 grid setup from before modelling the 2-bounce paths, you&#39;ll see that our top/bottom edges are both <span style="color:cyan">cyan</span> and our left/right edges are both <span style="color:gray">gray</span>, showing that exact relationship we&#39;d expect in a flat torus.</p>
<p><img src="/img/secure-squares/squareToTorus.gif"></p>
<center style="color: #666;">
<p>Connecting opposite edges of a square turns it into the equivalent of a torus.</p>
</center>

<p>This is the first key insight to solving this problem: turning our bouncing shots into straight lines in an infinitely tiled plane. Working with straight lines makes life so much easier than bent ones. With that, we can move on to the second epiphany to prove our result.</p>
<h3 id="the-different-core-4">The (Different) Core 4</h3>
<p>Even though we tile the plane infinitely, there aren&#39;t an infinite type of rooms. Just looking at our 2-by-2 grid that makes our flat torus shows us everything we need to know: there are exactly 4 types of rooms that build our tiling: the original one, the one reflected over the <span style="color:rgb(255,200,0)">yellow</span> wall, the one reflected over the <span style="color:magenta">magenta</span> wall, and the one reflected over <span style="color:rgb(255,200,0)">both</span> <span style="color:magenta">walls</span>. This regularity is clear visually: watch what happens if I reflect the <span style="color:green">target</span> into every mirrored room.</p>
<center>
<div id="secureLattice"></div>
</center>
<center style="color: #666;">
<p>Having 4 &quot;unique&quot; rooms generates 4 unique lattices of mirrored targets.</p>
</center>

<p>Each one of the reflected rooms generates a lattice of that reflected target! I&#39;ve colored the 4 different lattices in <span style="color:rgb(0,50,0)">green</span>, <span style="color:rgb(255,200,0)">yellow</span>, <span style="color:magenta">magenta</span>, and <span style="color:cyan">cyan</span>. Now, since each dot represents a way of hitting our <span style="color:green">target</span>, we just need to block every line from the <span style="color:red">assassin</span> to any one of these colored dots.</p>
<p>This is the second critical idea to finish out this proof: every reflected target falls into 1 of 4 possible lattices (each represented by a color). Dividing the mirrored targets into lattices is nice since it places all dots in a given lattice to be the same distance away from each other. </p>
<p>At this point, you have everything you need to finish this proof using the flat torus tiling and the 4 lattices. If you want to try and finish it through, I recommend doing so as it has some pretty satisfying reasoning throughout it. If you just want to keep reading, I&#39;d recommend visiting <a href="https://www.math3ma.com/blog/is-the-square-a-secure-polygon">Bradley&#39;s post</a> where she completes the proof there.</p>
<p>Once you reach the end of the proof, you&#39;ll find that you need exactly 4 bodyguards to protect any given lattice, and since there are 4 lattices, we need $4 \cdot 4 = 16$ bodyguards total to completely protect the <span style="color:green">target</span>.</p>
<center>
<div id="secureSquare"></div>
</center>
<center style="color: #666;">
<p>No matter where the <span style="color:red">assassin</span> shoots, the <span style="color:green">target</span> remains safe and sound. Try moving either of them around, and watch the bodyguards adapt and reduce the <span style="color:red">assassin</span>&#39;s efforts to nil.</p>
</center>

<p>Since it is possible to protect the <span style="color:green">target</span> from the <span style="color:red">assassin</span> with a finite number of <span style="color:blue">bodyguards</span>, we can say that the square is a <strong>secure polygon</strong>.</p>
<h2 id="what-next-">What Next?</h2>
<p>This is one of the most surprising facts I&#39;ve come across in a long time. But, there&#39;s more places to take these billiard problems and dynamical systems. One of the first extensions I thought of upon seeing this was other grids. <a href="http://xperimex.com/blog/grid-polygons/">As we know</a>, there are also hexagonal and triangular grids in addition to the square one we analyzed today.</p>
<p><div id="trihex_grid" style="flex: 2; position: relative;"></div></p>
<script src="/js/grid-polygons/trihex_grid.js"></script>
<center style="color: #666;">
<p>Examples of triangular (left) and hexagonal (right). Are they secure polygons?</p>
</center>

The regular triangle and hexagon seemed like the natural progression since they play nicely with reflections and tiling the plane, so they seemed like good candidates to explore next. But for anyone who's dabbled in linear algebra and transformations knows that reflections are only commutative if the axes are perpendicular. That's why squares worked well for tiling the plane since no matter what the order of the walls you reflected the <span style="color:green">target</span> over was, you'll get exactly one, unique "<span style="color:rgb(0,50,0)">mirrored target</span>" per reflected room. For triangles and hexagons, though, you <i>don't</i>, and that's an issue (superficially, at least; if anything, annoying). 

<br><br>

Not to mention, every other regular polygon doesn't tile the plane, so modelling their bouncing paths will be even more difficult. What about non-regular polygons? Or concave ones? This is definitely something I'll revisit in the future and try to find the conditions for a polygon to be secure, but until then, we have just scraped the surface of billiard problems and dynamical systems.

<hr>

A few other, related problems to consider. While we only looked at rays for light sources, others have considered other types of light sources. In an <a href="https://en.wikipedia.org/wiki/Illumination_problem">Illumination Problem</a>, we consider point sources (i.e. light source that produces light in every direction instead of one). Actually, we've already looked at one type of Illumination Problem: the secure square! It can be rephrased as the the following: if a light bulb is placed in a mirror room, is it possible to place a finite number of pillars such that a given spot is never illuminated? It's idential to our secure polygon question. One of my favorite Illumination Problems is the <a href="https://en.wikipedia.org/wiki/Art_gallery_problem">Art Gallery Problem</a>, which is not only a readily applicable problem, but also has a wonderfully elegant proof that Steve Fisk conjured (it speaks volumes how nice this proof is for it to be in Martin Aigner's <a href="https://www.amazon.com/Proofs-BOOK-Martin-Aigner-dp-3662572648/dp/3662572648/ref=mt_other?_encoding=UTF8&me=&qid="><i>Proofs from THE BOOK</i></a>). Here's a great, <a href="https://math.mit.edu/~apost/courses/18.204_2018/Nicole_Chesnokov_paper.pdf">in-depth paper</a> I found discussing this famous problem along with some proofs and extensions as well.

<br><br>

Even outside of classic billiard problems, even just knowing of the simple reflection technique to model bounces is invaluable. Grant Sanderson of 3blue1brown fame used bouncing light as an analogy to solve a <a href="https://www.youtube.com/watch?v=brU5yLm9DZM">kinematics problem</a> and bring in circles almost magically. I've said it before, and I'll say it again: duality and different perspectives are some of the most powerful problem solving tools you can have. This small reflection technique, or the complex number algebra with Alhazen's problem, might not mean much to you now, but it's another tool to stow away in your back pocket. Despite only seeing this ability to turn dynamics into geometry, I've seen them enough to know that these techniques and ideas are more than just an intriguing fact. You'll never know when you might be able to use such a tool, but when you do, who knows the new worlds that a new paradigm can unlock for you.

<hr>

If you're interested in learning a bit behind today's graphics and widgets, see the <a href="">follow up</a> I wrote up detailing some seemingly innocuous math with some high-budget applications and cool patterns.


<script src="/js/secure-squares/billiardIntroInstance.js"></script>
<!-- <script src="/js/secure-squares/billiardSolved.js"></script> -->
<script src="/js/secure-squares/billiardSolvedInstance.js"></script>


<!-- <script src="/js/secure-squares/alhazenIntroInstance.js"></script> -->
<script src="/js/secure-squares/alhazenIntro.js"></script>


<script src="/js/secure-squares/roomOneWall.js"></script>
<script src="/js/secure-squares/roomTwoWall.js"></script>
<script src="/js/secure-squares/roomSevenWall.js"></script>

<script src="/js/secure-squares/secureLattice.js"></script>



<script src="/js/secure-squares/secureSquareIntro.js"></script>
<script src="/js/secure-squares/secureSquare.js"></script>
]]></description>
         <link>http://xperimex.github.io/blog/secure-squares</link>
         <guid isPermaLink="true">http://xperimex.github.io/blog/secure-squares</guid>
         <dc:creator><![CDATA[Adi Mittal]]></dc:creator>
      </item>
      <item>
         <title><![CDATA[Circle Computations and Raytracing Remedies]]></title>
         <description><![CDATA[Basically, Pixar should hire me 

 <script src="//cdn.jsdelivr.net/npm/p5@1.4.0/lib/p5.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/g9/1.0.16/g9.js'></script>
<script src="https://www.desmos.com/api/v1.5/calculator.js?apiKey=dcb31709b452b1cf9dc26972add0fda6"></script>


<p>Last post, we looked at different types of <a href="http://xperimex.com/blog/secure-squares/">billiard problems</a>, a class of math problems analyzing how light bounces with different setups of mirrors. Notably, we saw how straight lines make for very simple, easy to compute mirrors, while others like <a href="https://en.wikipedia.org/wiki/Alhazen%27s_problem">circular ones</a>, can be incredibly frustrating. </p>
<p>A large portion of last post&#39;s content, though, was made up of interactive graphics. While I went over much of the math that goes into <em>solving</em> these types of problems, we skipped over a large part of the math that goes into <em>simulating</em> them. Math is very nice in that many problems can be solved with nothing more than a pen, paper, and your mind, but oftentimes, that&#39;s only helpful if you are confident in how to approach the problem. What computer&#39;s can do is help build our intuition to solve a problem by calculating, drawing, and modelling scenarios with precision and speed we can only wish to achieve.</p>
<p>So, today, we&#39;ll look at some of the clever math that goes into computer graphics (that we&#39;ll later extend), and to introduce such a topic, we&#39;ll look at a simple, fundamental problem in graphics: how do you find the intersection between a line and a circle?</p>
<h2 id="languishing-lines-and-confounding-circles">Languishing Lines and Confounding Circles</h2>
<p>Before we can even attempt this problem, we&#39;re going to have to start from scratch, since we have one <em>slight</em> issue: a computer has no idea what a line or a circle is! So before we can do anything, let&#39;s teach our computer how to draw a line.</p>
<h3 id="perfect-parameterizations">Perfect Parameterizations</h3>
<p>At its core, computer graphics is displaying a set of pixels with certain colors. If we want to visualize anything on a computer screen, we just need to find all the relevant pixels (coordinates) to light up and color. Because we want to compute these individual coordinates of, say, a line or circle very quickly and easily, almost always we will use <strong>vectors</strong>. These can be typical column or row vectors you see in linear algebra, or it can even take the form of complex numbers. The reason why these tend to be helpful is that they give very easy ways to compute coordinates for lines, circles, and other shapes.</p>
<p>If we want to draw a line with slope, say 2, we need to ensure that it is constructed by a vector of slope 2. An easy one to find is the vector $v=\small{\begin{bmatrix} 1 \\ 2 \end{bmatrix}}$ since we know that will pass through the point $(1,2)$. So, to get other points beyond this vector, we can scale $v$ by a factor of $t$ to get other vectors (i.e. points) with the same slope. If $t=2$, we get the point $(2,4)$. If $t=1.5$, we get the point $(1.5,3)$. If $t=239470$, we get the point $(239470,478940)$. Whatever you choose $t$ to be, our vector $v$ will give us a point on the line $y=2x$.</p>
<p>However, this isn&#39;t super helpful, since we are still only restricted to lines that go through the origin at $(0,0)$. So, we can add a starting point $\color{red}{p}$ to our vector equation to offset the line by $\color{red}{p}$, guaranteeing our line goes through the point $\color{red}{p}$ (since that&#39;s the coordinate generated by $t=0$).</p>
<center>
$\large{l = \color{red}{p} + tv}$
</center>

<p>Now we just plot every point for $t \in (-\infty, \infty)$, and we get a line with $v$ dictating the slope of our line (negative $t$ values gives us coordinates <em>behind</em> $\color{red}{p}$)!</p>
<center>
<div id="line"></div>
</center>
<center style="color: #666;">
<p>Our parametric line $l$ going through point $\color{red}{p}$. Drag the point to adjust it&#39;s position.</p>
</center>

<p>We can do a similar process for a circle. To parameterize a circle, we&#39;ll have to pull from trigonometry. We know that a circle is defined by $x^2 + y^2 = r^2$. The Pythagorean identity tells us that $\cos^2(\theta) + \sin^2(\theta) = 1$, so we can quickly make the connection that $x=r\cos(\theta)$ and $y=r\sin(\theta)$ (which the geometry justifies). This precisely defines $x$ and $y$ in terms of the parameter $\theta$! Again, though, this is centered at the origin, so we can center the circle around a point $\color{blue}{q}$ by adding it to our parameterization.</p>
<center>
$\large{c = \color{blue}{q} + r\begin{bmatrix} \cos(\theta) \\ \sin(\theta) \end{bmatrix}}$
</center>

<p>where $r$ is some real number for the radius of the circle, and $\theta \in [0, 2\pi)$. We can now easily draw both lines and circles!</p>
<center>
<div id="circle"></div>
</center>
<center style="color: #666;">
<p>Now we also have a circle centered at $\color{blue}{q}$ too. Drag the center point to change its position, and the radial point its radius.</p>
</center>


<h2 id="collisions-and-intersections">Collisions and Intersections</h2>
<p>Now that we have defined our line and circle for our computer to interpret, we can start thinking about how to detect collisions between a line and a circle. </p>
<h3 id="discerning-distances">Discerning Distances</h3>
<p>A good place to start is by looking at how far away the line $l$ is from the center of the circle $\color{blue}{q}$. For reference, the distance from a point to a line is the shortest (i.e. perpendicular) distance from the point to the line. If $l$ is more than a distance of $r$ away from $\color{blue}{q}$, then we know that it&#39;s outside the circle and doesn&#39;t intersect, and if $l$ is less than a distance $r$ away from $\color{blue}{q}$, then we know it&#39;s inside the circle and does intersect.</p>
<p><img src="/img/circle-computations/circleIntersectExample.png"></p>
<center style="color: #666;">
<p>$l_1$ is a distance less than $r$ away from the center, and clearly intersects the circle. $l_2$ is a distance greater than $r$ away, and clearly does not intersect the circle. $l_3$ is exactly a distance $r$ away, making it tangent to the circle (1 intersection point instead of 2).</p>
</center>

<p>Let&#39;s look at an individual line and see if we can draw any useful conclusions about this distance.</p>
<p><img src="/img/circle-computations/circleIntersectDist.png"></p>
<p>From a given point $\color{red}{p}$ on our line $l$, we can find a new vector between $\color{red}{p}$ and the circle&#39;s center $\color{blue}{q}$ as $\overrightarrow{\color{blue}{q} - \color{red}{p}}$. This will form some angle $\theta$ with $l$, more specifically its vector $v$. Recalling that $\color{green}{d}$ is the perpendicular distance between $\color{blue}{q}$ and $l$, we have a right triangle that gives us that $\color{green}{d} = |\overrightarrow{\color{blue}{q} - \color{red}{p}}| \sin \theta$.</p>
<p>If you&#39;re familiar with your linear algebra, this almost looks like the formula for the magnitude of the cross product: $|v \times u| = |v||u|\sin \theta$. So, writing our two relevant vectors and rearranging we can see that…</p>
<center>
$|\overrightarrow{\color{blue}{q} - \color{red}{p}}||v| \sin \theta = |\overrightarrow{\color{blue}{q} - \color{red}{p}} \times v|$
<br />
$|\overrightarrow{\color{blue}{q} - \color{red}{p}}| \sin \theta = |\overrightarrow{\color{blue}{q} - \color{red}{p}} \times \frac{v}{|v|}|$
</center>

<p>So all we need to do to see if our line intersects our circle is if that cross product is less than or equal to the radius of our circle (if you&#39;re concerned about the dimensionality of our vectors—cross products only exist in dimensions 3 and 7—we can treat them as 3D vectors with z-component 0, which makes the calculation easier and equivalent to the determinant). </p>
<p>If this isn&#39;t totally apparent why this is true, it has to do with the <a href="https://en.wikipedia.org/wiki/Cross_product#Geometric_meaning">geometrical interpretation</a> for the cross product: we&#39;re finding the area of the parallelogram that the two vectors span, and since the area of a parallelogram is $A=\textrm{base}\cdot\textrm{height}$, we&#39;re essentially finding the height of that parallelogram by dividing by its base.</p>
<center>
<div id="crossProduct"></div>
</center>
<center style="color: #666;">
<p>Using the closest distance between the circle and line, we can successfully identify when the line intersects our circle.</p>
</center>

<p>We have a working condition! Using the cross product, we can identify point-circle intersections with a single line of computation. However, this simple solution does have its limitations. Mainly, this is only a <strong>boolean</strong> condition; this method only tells us whether or not an intersection occurs, but nothing else. We don&#39;t know where on the line it intersects, nor how many times. Sometimes, this doesn&#39;t really matter like when you want to approximate lines intersecting points (since then you can treat points as small circles). But for more complex tasks and graphics like raytracing, this won&#39;t cut it.</p>
<h3 id="fancy-vector-operations">Fancy Vector Operations</h3>
<p>If we have a point $x$ on our circle, then the distance between $x$ and the center of the circle $\color{blue}{q}$ should be equal to the radius $r$. As an equation, the magnitude of the vector from $x$ to $\color{blue}{q}$ equals $r$.</p>
<center>
$|x - \color{blue}{q}| = r$
</center>

<p>Moreover, we want this point $x$ on our circle to also be on our line $l$. So, $x = \color{red}{p} + tv$ for some value of $t$. With this in mind, we can substitute $x$ in our previous equation.</p>
<center>
$|\color{red}{p} + tv - \color{blue}{q}| = r$
</center>

<p>Now, let&#39;s square both sides.</p>
<center>
$|\color{red}{p} + tv - \color{blue}{q}|^2 = r^2$
</center>

<p>This may seem pointless, but it helps us rewrite that left side of the equation. Generally, working with the magnitude of a vector as an operator isn&#39;t super helpful, but we can quickly rewrite the <em>square</em> of the magnitude in terms of the dot product, since for any vector $v \cdot v = |v|^2$. </p>
<center>
$(\color{red}{p} + tv - \color{blue}{q}) \cdot (\color{red}{p} + tv - \color{blue}{q}) = r^2$
</center>

<p>Expanding this out and collecting like terms gives us…</p>
<center>
$(\color{red}{p} + tv - \color{blue}{q}) \cdot (\color{red}{p} + tv - \color{blue}{q}) = r^2$
<br>
$t^2(v \cdot v) + 2t(v \cdot (\color{red}{p} - \color{blue}{q})) + (\color{red}{p} - \color{blue}{q}) \cdot (\color{red}{p} - \color{blue}{q}) - r^2 = 0$
</center>

<p>Which is just a quadratic equation in $t$! With coefficients…</p>
<center>
$\begin{align}
a &amp; = v \cdot v \
\newline
b &amp; = 2(v \cdot (\color{red}{p} - \color{blue}{q})) \
\newline
c &amp; = (\color{red}{p} - \color{blue}{q}) \cdot (\color{red}{p} - \color{blue}{q}) - r^2
\end{align}$
</center>

<p>…we can solve for $t$ using our trusted quadratic formula (note that $a$, $b$, and $c$ are all outputs of dot products, ensuring they are valid scalars to plug in).</p>
<center>
$\large{t = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}}$
</center>

<p>Remember, $t$ is the scalar that tells us where on our line we are, so if there are real solutions to $t$, then we will have the exact intersection points for our line and the circle!</p>
<center>
<div id="basicRaytrace"></div>
</center>
<center style="color: #666;">
<p>Our quadratic formula now not only tells us when the line intersects the circle, but also <em>where</em> they intersect.</p>
</center>

<p>We can analyze this quadratic like any other to give us insight into our intersection points. Specifically, using the discriminant. When $b^2 - 4ac &gt; 0$, then we get two solutions/intersection points. If $b^2 - 4ac &lt; 0$, then we get no real solutions and therefore no intersection points. Finally, if $b^2 - 4ac = 0$, then we have exactly one intersection point, and can conclude our line is tangent to the circle.</p>
<p>Also, this quadratic can straight up replace our closest-distance method from before, since the point at which our line is closest to the circle corresponds to the vertex of the parabola at $t=\frac{-b}{2a}$.</p>
<p>Not to mention, notice how everything we did here was independent of the fact our line and circle exist in two dimensions; we can easily use this for 3D graphics, and even higher dimensions as well to find the intersections between lines and hyperspheres! Below is a raytraced scene I drew of 3 balls using this exact quadratic to compute lighting with shadows and reflections (a.k.a. my formal application to Pixar).</p>
<p><img src="/img/circle-computations/rayTracedEx.png"></p>
<center style="color: #666;">
<p>This raytraced scene is just thousands of uses of the quadratic formula.</p>
</center>

<p>And to think that we&#39;d never use the quadratic formula in real life. </p>
<h2 id="i-don-t-know-where-else-to-put-this">I Don&#39;t Know Where Else to Put This</h2>
<p>Before I end off this post, I want to include some other interesting circle facts since I don&#39;t know where else to put them.</p>
<h3 id="squaring-the-circle-bounces-">Squaring the Circle (Bounces)</h3>
<p><strong>If you have a ray of light start from the circumference of the circle, after a total of $n$ reflections within the circle, the sum of all the angles of reflection will be $n^2$ times the initial angle.</strong></p>
<p>Between this and the <a href="https://en.wikipedia.org/wiki/Basel_problem">Basel problem</a>, circles and squares are just weirdly intertwined. The reason this particular statement is true is because of how much the angle with the horizontal increases after a single bounce. If your light starts at an angle $\alpha$, we can show that every additional bounce will add $2\alpha$ to the angle with respect to the horizontal.</p>
<p><img src="/img/circle-computations/oddBounce.png"></p>
<p>With the help of some auxiliary lines, I hope the above picture makes this clear. Then by symmetry, of the circle, we can see that each subsequent bounce will also add $2\alpha$ to the angle. Moreover, since our initial angle itself is $\alpha$, every bounce will just be the odd multiples of $\alpha$ (since odd numbers can be thought of as a multiple of 2 plus 1, which is precisely what our angle bounces mimic)! So, for a series of $n$ bounces, the sum of the angles of each reflection is equal to </p>
<center>
$\begin{align}
\alpha + 3\alpha + 5\alpha + 7\alpha + … + (2n-1)\alpha &amp; = \
\newline
\alpha(1+3+5+7+…+2n-1)&amp; = \
\newline
\alpha(n\cdot 1 + 2(0+1+2+3+…+n-1)&amp; = \
\newline
\alpha(n + 2\cdot\frac{(n-1)(n)}{2}) &amp; = \
\newline
\alpha(n + n^2 - n) &amp; = \alpha n^2
\end{align}$
</center>

<p>(Yes I am aware there is a formula for an arithmetic sequence with with any initial term but this is how I remember to solve them okay) I didn&#39;t know how to fit it in last post with the mention of circular mirrors there, but here seems like a good spot to mention it.</p>
<h3 id="perpendicular-parabolas">Perpendicular Parabolas</h3>
<p><strong>The set of intersection points between two orthogonal parabolas lie on a common circle.</strong></p>
<center>
  <div id="intro" style="width: 660px; height: 570px;"></div>

  <script src="/js/circle-computations/orthogonalParabolas.js"></script>
</center>

<p>To show this is true, we just need to crank out the algebra. To find our intersection points, we need to solve the system of equations</p>
<center>
$\begin{cases}
(x - \color{red}{x_1})^2 = y - \color{red}{y_1} \
\newline
(y - \color{blue}{y_2})^2 = x - \color{blue}{x_2}
\end{cases}$
</center>

<p>If these individual equations are true for our intersection points, then so is their sum.</p>
<center>
$(x - \color{red}{x_1})^2 + (y - \color{blue}{y_2})^2 = y - \color{red}{y_1} + x - \color{blue}{x_2}$
<br>
$x^2 - x(2\color{red}{x_1}) + \color{red}{x_1}^2 + y^2 - y(2\color{blue}{y_2}) + \color{blue}{y_2}^2 = y - \color{red}{y_1} + x - \color{blue}{x_2}$
<br>
$x^2 - x(2\color{red}{x_1} + 1) + y^2 - y(2\color{blue}{y_2} + 1) = -\color{red}{y_1} - \color{red}{x_1}^2 - \color{blue}{x_2} - \color{blue}{y_2}^2$
<br>
$(x - (\color{red}{x_1} + \frac{1}{2}))^2 - (\color{red}{x_1} + \frac{1}{2})^2 + (y - (\color{blue}{y_2} + \frac{1}{2}))^2 - (\color{blue}{y_2} + \frac{1}{2})^2 = -\color{red}{y_1} - \color{red}{x_1}^2 - \color{blue}{x_2} - \color{blue}{y_2}^2$
<br>
$(x - (\color{red}{x_1} + \frac{1}{2}))^2 + (y - (\color{blue}{y_2} + \frac{1}{2}))^2 = (\color{red}{x_1} + \frac{1}{2})^2 + (\color{blue}{y_2} + \frac{1}{2})^2  -\color{red}{y_1} - \color{red}{x_1}^2 - \color{blue}{x_2} - \color{blue}{y_2}^2$
</center>

<p>While that last line may seem a bit unruly, note that $\color{red}{x_1}$, $\color{red}{y_1}$, $\color{blue}{x_2}$, and $\color{blue}{y_2}$ are all constants, so the right-hand side of that last equation can be summarized as one big constant.</p>
<center>
$(x - (\color{red}{x_1} + \frac{1}{2}))^2 + (y - (\color{blue}{y_2} + \frac{1}{2}))^2 = C$
</center>

<p>That&#39;s precisely the equation of a circle with a center at $(\color{red}{x_1} + \frac{1}{2}, \color{blue}{y_2} + \frac{1}{2})$ and radius $\sqrt{C}$, and that&#39;s exactly what is plotted above.</p>
<hr>
<p>I have a few more circle tidbits to share, but they have more to expand on in their own posts for another day. </p>
<p>Until then, hopefully you found this slight detour into the world of graphics interesting. There are (as you could imagine) a lot more to graphics I want to share. From image homography, to video textures, to even a more in-depth look into raytracing and rasterization, but we&#39;ll save those for later.</p>
<script src="/js/circle-computations/line.js"></script>
<script src="/js/circle-computations/circle.js"></script>
<script src="/js/circle-computations/crossProduct.js"></script>
<script src="/js/circle-computations/basicRaytrace.js"></script>
]]></description>
         <link>http://xperimex.github.io/blog/circle-computations</link>
         <guid isPermaLink="true">http://xperimex.github.io/blog/circle-computations</guid>
         <dc:creator><![CDATA[Adi Mittal]]></dc:creator>
      </item>
      <item>
         <title><![CDATA[Incredible Integrals and Tactful Techniques]]></title>
         <description><![CDATA[Flexible? Maybe. Flex-able. Definitely 

 <p>This will be a slightly more theoretical, conceptual post than the others, but these tricks have that mathematical and problem-solving elegance that is too good not to share. We&#39;ll go over a shortcut for some certain integration by parts problems, and one that allows us to make educated guesses of antiderivatives to find an answer.</p>
<!-- Talk about IBP + C, ansatz, and maybe Feynmann's trick -->
<p>First, let&#39;s take a loot at the integration by parts shortcut.</p>
<h2 id="ibp-but-you-forgot-c">IBP, but You Forgot +C</h2>
<p>This is by far my new favorite trick to pull out of my back pocket whenever I can. It leverages the fact of the innate products built into integration by parts, and the nature of antiderivatives. Though, I&#39;m sure some of us could use a refresher on integration by parts.</p>
<h3 id="to-undo-the-product-rule">To Undo the Product Rule</h3>
<p>When given the product of two functions $f(x)g(x)$, the standard formula to compute its derivative is </p>
<center>
$\frac{\mathrm{d}}{\mathrm{d}x} \ f(x)g(x) = f&#39;(x)g(x) + f(x)g&#39;(x)$
</center>

<p>Now if you integrate both sides and rearrange a little bit we can conclude that</p>
<center>
$\int \frac{\mathrm{d}}{\mathrm{d}x} \ f(x)g(x) = \int f&#39;(x)g(x) \ dx + \int f(x)g&#39;(x) \ dx$
<br>
$\int f(x)g&#39;(x) \ dx = f(x)g(x) - \int f&#39;(x)g(x) \ dx$
</center>

<p>Let $u = f(x)$ and $v = g(x)$ to get that</p>
<center>
$\boxed{ \int u \ dv = uv - \int v \ du \hspace{.2cm} }$
</center>

<p>…which is precisely the integration by parts formula we&#39;ve come to know. It really just is the opposite of the product rule. The main reason why it&#39;s such a useful technique is because if you have a function that&#39;s really hard or you don&#39;t know how to integrate, you can use it as your function $u$ and express its integral purely in terms of its derivative. Let&#39;s try this with an example:</p>
<center>
$\int \ln x \ dx$
</center>

<p>This doesn&#39;t seem like a particularly product-y integral that can leverage integration by parts, but it really is!</p>
<center>
$\int \ln x \ dx = \int 1 \cdot \ln x \ dx$
</center>

<p>Since we don&#39;t want to deal with integrating $\ln x$ (besides, that&#39;s what we&#39;re trying to find anyway), we can set $u = \ln x$ and $dv = 1 \ dx$. Then working it through we get that</p>
<center>
$\int 1 \cdot \ln x \ dx = x \ln x - \int x \cdot \frac{1}{x} \ dx = x \ln x - x + C$
</center>

<p>That&#39;s pretty neat! We were able to reduce a relatively hard integral into one that was much simpler by thinking of it in terms of what product of functions when differentiated would include our original integral. </p>
<p>However, this doesn&#39;t always work by itself, and this is where our integral trick comes into play.</p>
<h2 id="now-remember-your-c">Now, Remember Your +C</h2>
<p>Let&#39;s try a very similar integral from before: </p>
<center>
$\int \ln(x+1) \ dx$
</center>

<p>This doesn&#39;t look too bad, right? It&#39;s basically the same as before. Let&#39;s try the same choice of $u = \ln(x+1)$ and $dv = 1 \ dx$ again and see where it takes us.</p>
<center>
$\int 1 \cdot \ln(x+1) \ dx = x \ln(x+1) - \int x \cdot \frac{1}{x+1} \ dx$
</center>

<p>Aaand there&#39;s our problem. Our supposed simplified integral of $\int v \ du$ ended up with something also annoying: $\int x \cdot \frac{1}{x+1} \ dx$. This isn&#39;t too bad if you&#39;re okay with polynomial division (with this one being relatively easy, too), but it isn&#39;t necessarily trivial. Since we want to avoid doing more work, we can do much better by realizing an overlooked aspect of integration by parts.</p>
<p>We rewrote our original integral in the form of $\int u \ dv$, and later found an antiderivative $v$ from that differential. In our case, we let $dv = 1 \ dx$ and deduced that $v = x$ by undoing the power rule of differentiation. This isn&#39;t <em>wrong</em>, per se, but it is incomplete. The antiderivative of $1\ dx$ isn&#39;t $x$, but $x \ \mathbf{+ \ C}$. Since, remember, the derivative of any constant goes to 0, we can add whatever constant we want to the end of our antiderivative and it&#39;ll still remain valid.</p>
<p>So how can this help us? Well, let&#39;s do the same integral with the same choice of $u$ and $dv$, but instead of letting $v = x$, let&#39;s make $v = x+1$.</p>
<center>
$\int 1 \cdot \ln(x+1) \ dx = (x+1) \ln(x+1) - \int (x+1) \cdot \frac{1}{x+1} \ dx$
</center>

<p>Look at that! That last, previously annoying integral, has become much simpler! Instead of getting two polynomials dividing each other, our new choice of $v$ reduces it to $\int (x+1) \cdot \frac{1}{x+1} \ dx = \int 1 \ dx = x + C$. So, finally, we can conclude that</p>
<center>
$\int \ln(x+1) \ dx = (x+1) \ln(x+1) - x + C$
</center>

<p>In fact, for any choice of a constant $\alpha$, we can see that</p>
<center>
$\int \ln(x+\alpha) \ dx = (x+\alpha) \ln(x+\alpha) - x + C$
</center>

<p>It&#39;s such a simple trick, but an important reminder to remember the basics and fundamentals when attempting a problem. Besides, $+C$ being more than a formality is at least a little bit satisfying.</p>
<h2 id="polynomial-predictions">Polynomial Predictions</h2>
<p>The last integral trick is a bit niche—it relies on that second integral when doing IBP to give a quotient two polynomials of matching degrees. This next shortcut, though, uses this idea of polynomial degree a bit more cleverly, but does not always work. When it does, though, it&#39;s certainly satisfying.</p>
<p>Let&#39;s find the following antiderivative:</p>
<center>
$\int \large{\frac{x^3 + 2x^2 + 3}{\sqrt{x^2 + 3}}}$ $dx$
</center>

<p>This doesn&#39;t look particularly friendly, but we can make some observations about this function. The numerator of our function is a cubic, or a polynomial of degree 3. Similarly, our denominator is the square root of a quadratic, or polynomial degree 2. In the very loose sense of &quot;degree&quot; we can say that asymptotically, the denominator is closer to a degree 1 or linear polynomial (yes, I know that that $\sqrt{x^2} = |x| \neq x$, but just play along for now). So, if we were to carry out all of the polynomial long division, we&#39;d expect our original function to behave like a degree $3 - \frac{2}{2} = 2$ polynomial.</p>
<p>Ok, so what? With basic integration, antidifferentiating a polynomial increases its degree by one. This is just the power rule.</p>
<center>
$\int x^{\color{red}{n}} \ dx = \frac{1}{n+1}x^{\color{red}{n+1}}$
</center>

<p>This fact implies that if our polynomial is loosely of &quot;degree&quot; 2, then integrating it should give us a function of degree $2+1=3$. So, let&#39;s make a guess at what our integral might look like.</p>
<center>
$\int \large{\frac{x^3 + 2x^2 + 3}{\sqrt{x^2 + 3}}}$ $dx = (ax^2 + bx + c)\sqrt{x^2+3}$
</center>

<p>This guess should look somewhat reasonable, since we have a quadratic multiplied by square root of another quadratic, which we loosely said was degree 1. And a polynomial of degree 2 multiplied by a polynomial of degree 1 gives us a polynomial of degree 3, which we wanted. However, you might wonder why we even wrote this as a product; why not just write this out as a pure cubic of $ax^3 + bx^2 + cx + d$? The main reason is expecting the chain rule of some kind to occur. When composing functions, the derivative—and therefore the integral—tend to include the structure of these compositions, so it&#39;s not unreasonable to make a guess with the denominator in the result.</p>
<p>Now here&#39;s the trick: let&#39;s differentiate both sides.</p>
<center>
$\large{\frac{x^3 + 2x^2 + 3}{\sqrt{x^2 + 3}}}$ $= (2ax + b)\sqrt{x^2+3} + (ax^2 + bx + c) \cdot \large{\frac{x}{\sqrt{x^2 + 3}}}$
</center>

<p>If we simplify this expression and expand the right side…</p>
<center>
$\large{\frac{x^3 + 2x^2 + 3}{\sqrt{x^2 + 3}}}$ $= (2ax + b)\sqrt{x^2+3} + (ax^2 + bx + c) \cdot \large{\frac{x}{\sqrt{x^2 + 3}}}$
<br>
$x^3 + 2x^2 + 3 = (2ax + b)(x^2+3) + (ax^2 + bx + c) \cdot x$
<br>
$x^3 + 2x^2 + 3 = 3ax^3 + 2bx^2 + (6a + c)x + 3b$
</center>

<p>For this last equation to hold, we need the coefficients to match.</p>
<center>
$\color{red}{x^3} + \color{blue}{2x^2} + \color{green}{0x} + \color{purple}{3} = \color{red}{3ax^3} + \color{blue}{2bx^2} + \color{green}{(6a + c)x} + \color{purple}{3b}$
</center>

<p>Therefore,</p>
<center>
$\begin{align}
a &amp; = \frac{1}{3} \
\newline
b &amp; = 1 \
\newline
c &amp; = -2
\end{align}$
</center>

<p>Putting it all together, we can go back to our original guess of the antiderivative and find that</p>
<center>
$\int \large{\frac{x^3 + 2x^2 + 3}{\sqrt{x^2 + 3}}}$ $dx = \boxed{\ (\frac{1}{3}x^2 + x - 2)\sqrt{x^2+3} + C \ }$
</center>

<p>There we go! A succcessful antiderivative found.</p>
<p>This is trick is a great first attempt at integrating rational functions, but it is also extremely sensitive to minute changes in the integrand. For example, if we change our integral to</p>
<center>
$\int \large{\frac{x^3 + 2x^2 + \color{red}{3}}{\sqrt{x^2 + 3}}}$ $dx \rightarrow \int \large{\frac{x^3 + 2x^2 + \color{red}{2}}{\sqrt{x^2 + 3}}}$ $dx$
</center>

<p>our algorithm breaks. It&#39;s the cost associated with what makes this algorithm so convenient: we don&#39;t touch the numerator of the integrand at all. Our antiderivative guess only depended on the denominator, and as a result, the coefficients we tried to match at the end had no intrinsic tie to the numerator and thus polynomial we were matching. </p>
<p>This integral shortcut&#39;s convenience is definitely a double-edged sword, but the method behind making these educated guesses is a useful idea in its own right to take away. For more on this type of integration, I recommend reading up on the <a href="https://en.wikipedia.org/wiki/Risch_algorithm">Risch algorithm</a>, a standard in computing indefinite integrals. Here&#39;s also <a href="https://blog.wolfram.com/2021/08/18/new-methods-for-computing-algebraic-integrals/">a very thorough synopsis</a> on evaluating integrals on the Wolfram Blog.</p>
<h2 id="feynman-s-at-it-again">Feynman&#39;s At It Again</h2>
<p>This last integration stratagem comes from none other than the celebrated Richard Feynman of physics fame, and thus has been aptly coined as Feynman&#39;s Intregral Trick.</p>
<p>…as it has been popularized. What I&#39;m about to show has historically been known as the <a href="https://en.wikipedia.org/wiki/Leibniz_integral_rule">Leibniz Integral Rule</a>, or differentiation under the integral sign. Not quite the same ring to it, but nonetheless good to know for accuracy.</p>
<p>Let&#39;s try the following integral:</p>
<center>
$\int_{0}^{1} \large{\frac{x^2 - 1}{\ln x}}$ $dx$
</center>

<p>What we&#39;re about to do might seem insane, but it will be immensely helpful in a second. What we&#39;re going to do is <em>generalize</em> this integral. Let</p>
<center>
$f(\color{red}{t}) = \int_{0}^{1} \large{\frac{x^\color{red}{t} - 1}{\ln x}}$ $dx$
</center>

<p>We&#39;ve replaced the exponent of 2 with a $t$. So, in our new, generalized problem, we want to find $f(2)$. A useful fact also to note is that we know some values of $f(t)$. For example, we know that $f(0)=0$. How does this help? Well, now we can what the name of this trick alludes to—moreso outright says: we&#39;ll differentiate under the integral sign. Let&#39;s take the derivative of $f(t)$ with respect to $t$. </p>
<center>
$\large{\frac{\partial f}{\partial t}}$ $= \large{\frac{\partial}{\partial t}}$ $\int_{0}^{1} \large{\frac{x^{t} - 1}{\ln x}}$ $dx = \int_{0}^{1} \large{\frac{\partial}{\partial t} \frac{x^{t} - 1}{\ln x}}$ $dx = \int_{0}^{1} x^t \ dx$
</center>

<p>That last integral is super easy, only reversing the power rule to calculate.</p>
<center>
$\large{\frac{\partial f}{\partial t}}$ $= \int_{0}^{1} x^t \ dx = \large{\frac{x^{t+1}}{t+1}}$ $|_{0}^{1} = \large{\frac{1}{t+1}}$
</center>

<p>Now that we know the derivative of $f(t)$, we can now integrate this simpler function in terms of known values and use the Fundamental Theorem of Calculus to find $f(2)$. </p>
<center>
$\int_{0}^{2} \partial f = f(2) - f(0) = f(2) = \int_{0}^{2} \large{\frac{1}{t+1}}$ $\partial t = \ln3 - \ln 1 = \boxed{\ln 3 }$
</center>

<p>Note how I used the Fundamental Theorem of Calculus with clever bounds for our integral. You could instead solve the differential equation generally, but the FTC skips shortcuts a few steps. So, after all of that, we can conclude </p>
<center>
$\int_{0}^{1} \large{\frac{x^2 - 1}{\ln x}}$ $dx = \ln 3$
</center>

<p>As counterintuitive as it may seem, solving a general problem can sometimes actually be easier to solve than its individual cases. The best part about this technique, though, is that we haven&#39;t just solved one integral, but a whole <em>family</em> of integrals. For any exponent $\alpha$, we can conclude that</p>
<center>
$\int_{0}^{1} \large{\frac{x^\alpha - 1}{\ln x}}$ $dx = \ln (\alpha + 1)$
</center>

<p>You might have noticed something different with this integral compared to our previous approaches: this applies to <em>definite</em> integrals as opposed to <em>indefinite</em> integrals (or antiderivatives). Namely, because of the fact we have to integrate not once but twice in this method. So, at the following step,</p>
<center>
$\large{\frac{\partial f}{\partial t}}$ $= \int_{0}^{1} x^t \ dx = \large{\frac{x^{t+1}}{t+1}}$ $|_{0}^{1} = \large{\frac{1}{t+1}}$
</center>

<p>if this was not a definite integral, we would end up with a $+C$ attached to the end of it that we would not be able to solve for. </p>
<p>Here&#39;s another application of Feynman&#39;s trick:</p>
<center>
$\int_{0}^{1} \large{\frac{\ln (x+1)}{x^2 + 1}}$ $dx$
</center>

<p>Knowing Feynman&#39;s trick wins you the battle, but knowing <em>how</em> to use it wins you the war. Many times, you have to be creative in your choice of parameter when wanting to differentiate under the integral sign, so don&#39;t be discouraged if it doesn&#39;t work the first time. For this particular integral, we&#39;ll want to consider</p>
<center>
$f(t) = \int_{0}^{1} \large{\frac{\ln (tx+1)}{x^2 + 1}}$ $dx$
</center>

<p>Now, we want to find $f(1)$, and we know that $f(0)=0$. Now let&#39;s differentiate both sides with respect to $t$.</p>
<center>
$\large{\frac{\partial f}{\partial t}}$ $= \int_{0}^{1} \large{\frac{\partial}{\partial t} \frac{\ln (tx+1)}{x^2 + 1}}$ $dx = \int_{0}^{1} \large{\frac{x}{(tx+1)(x^2 + 1)}}$ $dx$
</center>

<p>Decomposing that last integral into its partial fractions yields</p>
<center>
$\large{\frac{\partial f}{\partial t}}$ $= \int_{0}^{1} \large{\frac{x}{(tx+1)(x^2 + 1)}}$ $dx = \large{\frac{1}{t^2 + 1}}$ $\int_{0}^{1} \large{\frac{-t}{tx+1}}$ $+ \large{\frac{x}{x^2+1}}$ $+ \large{\frac{t}{x^2 + 1}}$ $dx$
</center>

<p>Now, with more elementary calculus, we can evaluate that integral.</p>
<center>
$\int_{0}^{1} \large{\frac{-t}{tx+1}}$ $+ \large{\frac{x}{x^2+1}}$ $+ \large{\frac{t}{x^2 + 1}}$ $dx = -\ln(tx+1) + \frac{1}{2}\ln(x^2+1) + t\tan^{-1}(x) |_{0}^{1}$
<br><br>
$\large{\frac{\partial f}{\partial t}}$ $=\large{\frac{-4\ln(t+1) + 2\ln(2) + t\pi}{4(t^2 + 1)}}$
</center>

<p>Now, we want $f(1)$, and know that $f(0)=0$, so let&#39;s integrate this function of $t$ from 0 to 1.</p>
<center>
$f(1) = \int_{0}^{1} \large{\frac{-4\ln(t+1) + 2\ln(2) + t\pi}{4(t^2 + 1)}}$ $\partial t = \int_{0}^{1} \large{\frac{2\ln(2) + t\pi}{4(t^2 + 1)}}$ $\partial t + \int_{0}^{1} \large{\frac{-4\ln(t+1)}{4(t^2 + 1)}}$ $\partial t$
<br><br>
$f(1) = \int_{0}^{1} \large{\frac{2\ln(2) + t\pi}{4(t^2 + 1)}}$ $\partial t - \int_{0}^{1} \large{\frac{\ln(t+1)}{t^2 + 1}}$ $\partial t = \int_{0}^{1} \large{\frac{2\ln(2) + t\pi}{4(t^2 + 1)}}$ $\partial t - f(1)$
<br><br>
$f(1) = \large{\frac{1}{2}}$ $\int_{0}^{1} \large{\frac{2\ln(2) + t\pi}{4(t^2 + 1)}}$ $\partial t = \large{\frac{\pi \ln 2}{8}}$
</center>

<p>Again, almost magically, by generalizing a hard integral, it became a much easier one to tackle.</p>
<center>
$\int_{0}^{1} \large{\frac{\ln (x+1)}{x^2 + 1}}$ $dx = \large{\frac{\pi \ln 2}{8}}$
</center>

<p>To give you an idea how powerful this technique is, the above integral comes from the <a href="https://kskedlaya.org/putnam-archive/2005.pdf">2005 Putnam Exam</a>. Not only does it come from one of the most difficult math tests, it&#39;s also the 5th problem of the first set of problems (with problem 1 being the &quot;easiest&quot; and 6 being near impossible). And, in only a few lines, Feynman and Leibniz had it beat.</p>
<h2 id="conclusion">Conclusion</h2>
<p>These are the three most recent integration techniques I have picked up and tucked away in my problem solving toolbox, but if you&#39;re interested in more advanced integral shortcuts and tricks, take a look at this <a href="https://math.stackexchange.com/questions/942263/really-advanced-techniques-of-integration-definite-or-indefinite/943212">MathStackExchange post</a> I came across while doing this write-up. There are some genuinely mesmerizing ideas showcased there that just are out of the scope of my ability to explain, so do browse the forum if you&#39;re interested.</p>
]]></description>
         <link>http://xperimex.github.io/blog/incredible-integrals</link>
         <guid isPermaLink="true">http://xperimex.github.io/blog/incredible-integrals</guid>
         <dc:creator><![CDATA[Adi Mittal]]></dc:creator>
      </item>
      <item>
         <title><![CDATA[The Calculus of Variations]]></title>
         <description><![CDATA[The end of an era 

 <p>It&#39;s a been a little while since I&#39;ve last posted. As part of my calculus class, we end the year with an exploration into a calculus related topic that we present to the rest of the class. I and my partner chose to explore the origins behind the <em>brachistochrone</em>: the curve of fastest descent for a rolling ball. Below is the related write-up I did as part of this project, and thought it might make for a good posting. It helped refine my LaTeX skills and I think is a good introduction into the field and motivations of the <em>calculus of variations</em>. Now that summer is right around the corner, hopefully I&#39;ll be able to write more in the coming months. For now, I hope this will do. </p>
<object data="/img/The_Brachistochrone_and_the_Calculus_of_Variations.pdf" type="application/pdf" width=100% height="895px">
    <iframe src="https://docs.google.com/viewer?url=https://mittal.ai/docs/resume.pdf&embedded=true" width="100%" height="2000px"></iframe>
</object>
]]></description>
         <link>http://xperimex.github.io/blog/variational-calculus</link>
         <guid isPermaLink="true">http://xperimex.github.io/blog/variational-calculus</guid>
         <dc:creator><![CDATA[Adi Mittal]]></dc:creator>
      </item>
      <item>
         <title><![CDATA[<i>Quake III</i>'s Smartest Quasi-Square Root]]></title>
         <description><![CDATA[See? Video games ARE useful 

 <p>A couple months back, <a href="http://xperimex.com/blog/circle-computations/">we covered a little bit about some random circle computations and facts</a> I had collected over the months leading into that post. In it, we highlighted and rederived the basic raytracing equation for circles and spheres. In a few words, we used properties of vectors to be able to reduce the problem of where a line intersects a sphere into a quadratic equation. And with all quadratics, we were then able to use the quadratic formula to quickly find those points of intersection. In that post, I go on to say that I was able to generate this <em>incredible</em> raytraced scene in a mere matter of tens of minutes in even as simple a programming language as Python:</p>
<p><img src="/img/circle-computations/rayTracedEx.png"></p>
<center style="color: #666;">
<p>This raytraced scene is just millions of uses of the quadratic formula.</p>
</center>

<p>But I have to admit, I sort of lied to you. While, yes, that image <em>does</em> use the quadratic formula millions of times, it doesn&#39;t <em>only</em> do that. To render shadows and reflections, the scene also had to compute lighting and the physics you&#39;d expect with mirror-like objects. Without any of this, our scene would just look like, well, uh, this:</p>
<p><img src="/img/fast-sqrt/badRaytrace.png"></p>
<center style="color: #666;">
<p>Now <i>this</i> is a peak graphical performance. In a word: art.</p>
</center>

<p>Whichever one you think is better looking is up to the eye of the beholder, but what can&#39;t be argued, is that the second image is much cheaper to render; I&#39;m sure you could guess, no shadows and reflections causes the scene to be rendered in a fifth of the time. <em>A fifth</em>.</p>
<h2 id="quizzing-quotients">Quizzing Quotients</h2>
<p>Intuitively, more stuff to compute should take a computer a longer amount of time to go through, but can we pinpoint this bottleneck? Let&#39;s quickly look at what it takes to compute some of these reflections. When light bounces off, say, a mirror, these calculations become much easier when we use the mirror or surface&#39;s <em>normal vector</em>: the vector perpendicular to the surface (or the point at the surface) in question.</p>
<p><img src="/img/fast-sqrt/reflectRay.png"></p>
<center style="color: #666;">
<p>How to reflect a ray over a normal vector.</p>
</center>

<p>The above formula for reflecting a ray works in general for reflecting any ray $\vec{R}$ over another vector $\vec{N}$ (even if they&#39;re not normal)… Under a small assumption: the vector $\vec{N}$ is <em>normalized</em> (yes, the naming scheme isn&#39;t ideal), or of unit length (denoted by a little hat $\hat{N}$). We can do this by just scaling the vector down by its own length:</p>
<center>
$$\hat{N} = \large{ \frac{\vec{N}}{\lVert N \rVert} }$$
</center>

<p>Recalling that the length of a vector 3D $\lVert N \rVert = \lVert &lt;x,y,z&gt; \rVert = \sqrt{x^2 + y^2 + z^2}$, we end up with </p>
<center>
$$\hat{N} = \large{ \frac{\vec{N}}{\sqrt{x^2 + y^2 + z^2}} }$$
</center>

<p>And here lies our bottleneck. While we, as humans, treat division not too differently from multiplication in theory, computers can&#39;t work with &quot;just in theory&quot;; computers have to actually compute this arithmetic somehow. It turns out, while multiplication is a bit more complicated than addition, we&#39;ve been able to make <a href="https://en.wikipedia.org/wiki/Karatsuba_algorithm">algorithms</a> for <em>decades</em> to accelerate the computation. Division, on the other hand, has been such a difficult endeavor to match other operations speed, major companies like Intel have lots of <a href="https://www.cl.cam.ac.uk/~jrh13/papers/hol00.pdf">research dedicated to this alone</a>.</p>
<p>So, what do we do?</p>
<h2 id="the-fast-inverse-square-root">The Fast Inverse Square Root</h2>
<p>Under pressure, people can do some amazing things. You can imagine if someone was making a game or anything that required lots of lighting calculations, say, in a video game, calculating $\frac{1}{\sqrt{x}}$ millions of times, therefore also computing millions of divisions won&#39;t really cut it. </p>
<p>The developers of the video game <em>Quaker III</em>, an incredibly fast-paced shooter that definitely needed these optimizations, used a now infamous algorithm aptly called the <em>fast inverse square root</em>, because, well, it computes the inverse square root $\frac{1}{\sqrt{x}}$, fast and avoids dreaded division. The history of the algorithm has been found to predate the game that made it so infamous, but pop culture assigns value to whatever it latches onto first. Without further ado, the original source code (along with all the original comments and annotations) for <em>Quake III</em> was released in 2005, and the program is right there for us to learn from:</p>
<div style="background: #f8f8f8; overflow:auto;width:auto;border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em; font-size: 12px"><pre style="margin: 0; line-height: 125%"><span style="color: #B00040">float</span> <span style="color: #0000FF">Q_rsqrt</span>( <span style="color: #B00040">float</span> number )
{
      <span style="color: #B00040">long</span> i;
      <span style="color: #B00040">float</span> x2, y;
      <span style="color: #008000; font-weight: bold">const</span> <span style="color: #B00040">float</span> threehalfs <span style="color: #666666">=</span> <span style="color: #666666">1.5F</span>;

      x2 <span style="color: #666666">=</span> number <span style="color: #666666">*</span> <span style="color: #666666">0.5F</span>;
      y  <span style="color: #666666">=</span> number;
      i  <span style="color: #666666">=</span> <span style="color: #666666">*</span> ( <span style="color: #B00040">long</span> <span style="color: #666666">*</span> ) <span style="color: #666666">&amp;</span>y;                     <span style="color: #408080; font-style: italic">// evil floating point bit level hacking</span>
      i  <span style="color: #666666">=</span> <span style="color: #666666">0x5f3759df</span> <span style="color: #666666">-</span> ( i <span style="color: #666666">&gt;&gt;</span> <span style="color: #666666">1</span> );             <span style="color: #408080; font-style: italic">// what the fuck? </span>
      y  <span style="color: #666666">=</span> <span style="color: #666666">*</span> ( <span style="color: #B00040">float</span> <span style="color: #666666">*</span> ) <span style="color: #666666">&amp;</span>i;
      y  <span style="color: #666666">=</span> y <span style="color: #666666">*</span> ( threehalfs <span style="color: #666666">-</span> ( x2 <span style="color: #666666">*</span> y <span style="color: #666666">*</span> y ) ); <span style="color: #408080; font-style: italic">// 1st iteration</span>
<span style="color: #408080; font-style: italic">//    y  = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed</span>

      <span style="color: #008000; font-weight: bold">return</span> y;
}
</pre></div>


<p>It&#39;s not a long algorithm by any means, but I think the comments themselves explain just how crazy this is; even the developers who USED it are impressed, but let&#39;s break it down line by line.</p>
<div style="background: #f8f8f8; overflow:auto;width:auto;border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em;"><pre style="margin: 0; line-height: 125%">      <span style="color: #B00040">long</span> i;
      <span style="color: #B00040">float</span> x2, y;
      <span style="color: #008000; font-weight: bold">const</span> <span style="color: #B00040">float</span> threehalfs <span style="color: #666666">=</span> <span style="color: #666666">1.5F</span>;
</pre></div>

<p>Here we define four different numbers: <code>i</code>, <code>x2</code>, <code>y</code>, and <code>threehalfs</code>. But not all of these numbers are treated the same.</p>
<h3 id="binary-and-floating-point">Binary and Floating Point</h3>
<p>In our day-to-day routine, we (at least, most of us) use base 10, decimal, to represent our numbers. What this means is that each digit in a number corresponds to some power of 10 we add together. For example, the number 1409, can be grouped as</p>
<center>
$
\begin{array}{c|c|c|c}
1 &amp; 4 &amp; 0 &amp; 9 \\ \hline
10^3 &amp; 10^2 &amp; 10^1 &amp; 10^0  \\
\end{array}
$
</center>

<p>with 1 thousands, 4 hundred, 0 tens, and 9 ones. You add these all together to get $1(10^3) + 4(10^2) + 0(10^1) + 9(10^0) = 1409$. This may seem obvious, but this is a really important idea in how we write numbers. Each digit represents a condensed shorthand for how many of a specific power of 10 is in our number. Computers do it similarly, but instead of base 10, they use base 2, or binary. If we wanted to represent 1409 in binary, we&#39;d have</p>
<center>
$
\begin{array}{c|c|c|c|c|c|c|c|c|c|c}
1 &amp; 0 &amp; 1 &amp; 1 &amp; 0 &amp; 0 &amp; 0 &amp; 0 &amp; 0 &amp; 0 &amp; 1 \\ \hline
2^{10} &amp; 2^9 &amp; 2^8 &amp; 2^7 &amp; 2^6 &amp; 2^5 &amp; 2^4 &amp; 2^3 &amp; 2^2 &amp; 2^1 &amp; 2^0  \\
\end{array}
$
</center>

<p>Now if you went and added these together you could verify that $2^{10} + 2^{8} + 2^{7} + 2^{0} = 1409$. Now each digit—or decimal-igit—represents a power of 2. We call these binary-igits bits. That first line of code that defines a <code>long i</code> means we define a number with 32 bits that looks like</p>
<center>
<code>00000000 00000000 00000000 00000000</code>
</center>

<p>With 32 bits, we can write any number from 0 to $2^{32} - 1 = 4294967295$. Let&#39;s notice some nice properties with this format. In decimal, if we wanted to add a 0 to the end of our number like $1409 \rightarrow 14090$, this is the same as multiplying our number by 10, because now every digit has moved up into one bucket higher than before.</p>
<center>
$
\begin{array}{c|c|c|c|c}
1 &amp; 4 &amp; 0 &amp; 9 &amp; 0\\ \hline
10^4 &amp; 10^3 &amp; 10^2 &amp; 10^1 &amp; 10^0  \\
\end{array}
$
</center>

<p>In the same way, we can remove zeroes on the right $14090 \rightarrow 1409$ by dividing by 10 since every digit will be shifted into one power lower. Binary works the same. If we want to add a 0 to the right end of our number, we now multiply our number by 2, but if we wanted to remove a 0, we divide by 2. This is known as <strong>bit shifting</strong>, and serves as one of the nice workarounds of division: if you want to divide specifically by a power of 2, just bit shift the number in binary by however many zeroes you need.</p>
<p>But that leads to an issue: only even numbers can be wholly divided by 2, so what do we do if we want to divide an odd number? How would we write a decimal like .5? How would we write any rational number? We currently can only represent 32-bit <em>integers</em>, since we have no way of writing fractional parts. If we wanted to add decimals, why don&#39;t we just throw in a decimal point then?</p>
<center>
<code>00000000 00000000 . 00000000 00000000</code>
</center>

<p>(Remember this decimal point is just for our convenience; the computer doesn&#39;t actually see anything here but the 32 bits) If we use the left 16 bits for the integer part, and the right 16 bits for the decimal, we can now in fact write rational numbers, but all of a sudden the range of numbers we can represent has shrunk immensely, only to just under 65535.9999847, but the upside is now we can do much more precise, rational numbers. This is okay, but we can do better. </p>
<p>If you have ever taken a chemistry or physics class, you&#39;re probably all too familiar with <em>scientific notation</em>. We can write really big numbers and really small numbers in a much more condensed way by turning everything into a product of a power of ten:</p>
<center>
$\begin{align}
4230987 &amp; \rightarrow 4.230987 \cdot 10^6 \
\newline
0.000154 &amp; \rightarrow 1.54 \cdot 10^{-4}
\end{align}$
</center>

<p>This is how our calculators can do arithmetic beyond just the digits shown on the screen. By slapping on a power of 10, we can now represent a much wider range of values using the same number of digits previously. Similarly, binary works just the same except with powers of 2.</p>
<center>
$\begin{align}
11010111 &amp; \rightarrow 1.1010111 \cdot 2^7 \
\newline
0.00101 &amp; \rightarrow 1.01 \cdot 2^{-3}
\end{align}$
</center>


<p>So, let&#39;s do just that. Let&#39;s allocate 8 bits of our previous 32 to representing the <span style="color:green">exponent</span>, and another 23 to our <span style="color:blue">actual number</span>.</p>
<center>
<span style="color:green"><code>00000000</code></span> <span style="color:blue"><code>0.0000000000000000000000</code></span>
</center>

<p>With 8 bits for the <span style="color:green">exponent</span>, we can represent anything from 0 to 255, but we also want negative exponents, so we just subtract 127 to get the new range of exponents from -127 to 128. With our <span style="color:blue">fractional number</span> and its 1 whole bit and 22 decimal bits, we can represent numbers from 0 to 1.999999761581. We call this part of the number the <span style="color:blue">mantissa</span>. However, this is actually not the full extent of the potential precision we can get. In all of our examples of scientific notation, there was always a non-zero number before the decimal point, since if there was a leading 0, that&#39;s another power of our exponent we could factor out. In binary, there&#39;s only two values: 0 and 1. If we know the first digit is non-zero, then we know it has to be a 1! So we can actually shift our decimal point over and gain an extra bit.</p>
<center>
<span style="color:green"><code>00000000</code></span> <span style="color:blue"><code>.00000000000000000000000</code></span>
</center>

<p>Now all we have to do is affix a leading 1 and we&#39;re good to go. So, the number</p>
<center>
<span style="color:green"><code>11001010</code></span> <span style="color:blue"><code>.01110100000000000000000</code></span>
</center>

<p>would represent $1\color{blue}{.453125} \cdot \color{green}{2^{202-127}}$. In general, if we&#39;re given a 23 bit number representing the <span style="color:blue">mantissa</span> and an 8 bit number representing the <span style="color:green">exponent</span>, we can write our number we&#39;re expressing as:</p>
<center>
$\large{(1 + \color{blue}{\frac{M}{2^{23}}}) \cdot \color{green}{2^{E-127}}}$
</center>

<p>We divide our <span style="color:blue">mantissa</span> by $2^{23}$ so that it is only the fractional part of our number like we want. However, doesn&#39;t part of this just <em>feel</em> wrong? Like, when we were defining an integer as a 32 bit <code>long</code>, we used every bit to denote a new power of 2. Here, we really are writing two <em>different</em> binary numbers side-by-side. If we wrote our number as </p>
<center>
<span style="color:blue"><code>.01110100000000000000000</code></span> <span style="color:green"><code>11001010</code></span>
</center>

<p>would it really make a difference? So, just for the sake of consistency, we&#39;ll put the <span style="color:green">exponent</span> first, and we can then represent our number&#39;s bit representation as a sum:</p>
<center>
$\begin{align}
\color{green}{00000000} 00000000000000000000000 &amp; \
\newline
\color{blue}{00000000000000000000000} &amp; \ 
\newline
\hline
\color{green}{00000000}\color{blue}{00000000000000000000000}
\end{align}$
</center>

<p>We just added 23 filler zeroes to our exponent to make sure it landed where we wanted to in the final bit representation. That sounds like a bit shift! We can thus multiply our <span style="color:green">exponent</span> by $2^{23}$ to give us our 23 extra zeroes So, this final sum—our <span style="color:green">exponent</span> and <span style="color: blue">mantissa</span> together—can be written as</p>
<center>
$\large{ \color{green}{E}\cdot 2^{23} + \color{blue}{M} }$
</center>

<p>Now, there are some flaws that do need to be addressed. If we assume our leading bit is non-zero, how _do_ we represent 0? That actually doesn&#39;t matter in the grand scheme of our intended use in lighting (i.e. we only call the fast inverse square root when we <em>have</em> to use it), and when we&#39;re not, this is a single edge case that can be put in later. Yeah, I&#39;ll admit, it&#39;s not ideal, but it gives us more precision where we need it. The other issue is we haven&#39;t used all of our 32 bits! $8+23=31$, so where did our last bit go? In our set-up, we have it such that we can only represent <em>positive</em> numbers. We can attach an additional <em>sign bit</em> at the front, where if it&#39;s a 0, we say the number is positive, and if it&#39;s a 1, the number is negative. </p>
<center>
<span style="color:red"><code>0</code></span> <span style="color:green"><code>11001010</code></span> <span style="color:blue"><code>.01110100000000000000000</code></span>
</center>

<p>However, we want to know how to find <em>positive</em> square roots, not enter the complex world, so we always just assume it&#39;s positive. So if we don&#39;t use the bit, why don&#39;t we repurpose it? Conventions. The standard for binary fractional-part representation and arithmetic is known as <strong>IEEE 754</strong>, and for that reason we just have to abide by it.</p>
<p>I&#39;ve been calling this with terms like &quot;decimal points&quot; and &quot;fractional-parts&quot;, but a decimal point seems wrong when we&#39;re doing it in binary. The type of number we&#39;ve just formatted is called a <em>floating point</em> or a <code>float</code> as we see in lines 2 and 3. While <code>float</code>s give us nice ways to represent a lot of numbers, they are a bit annoying compared to <code>long</code>s in the sense that <strong>we can&#39;t bit shift or manipulate a <code>float</code></strong> since the bits in a <code>float</code> represent multiple, different parts of the number in question, namely the <span style="color:green">exponent</span> and the <span style="color:blue">mantissa</span>.</p>
<!-- ---------- -->
<h3 id="bit-approximations-with-themselves-">Bit Approximations… With Themselves?</h3>
<p>This may seem like a gross, unnecessary dive into how computers understand numbers, but understanding what binary, bits, and floats are will help us greatly in understanding the ingenuity behind the fast inverse square root. To recap, we&#39;ve found that we can represent a binary number as a <code>float</code> with two parts, an <span style="color:green">exponent</span> and a <span style="color:blue">mantissa</span>, as if we were using scientific notation. To find the actual number our <code>float</code> represents, we use the formula</p>
<center>
$\large{(1 + \color{blue}{\frac{M}{2^{23}}}) \cdot \color{green}{2^{E-127}}}$
</center>

<p>Since we&#39;re working with two different binary numbers together, we combine them into one sequence of bits that to as a shorthand to represent our <code>float</code> with the formula</p>
<center>
$\large{ \color{green}{E}\cdot 2^{23} + \color{blue}{M} }$
</center>

<p>We can now perform some mathematical magic. Let&#39;s take the logarithm of the actual number of our <code>float</code> (note by $\log(x)$, we assume it to be $\log_2(x)$ since we&#39;re working in binary).</p>
<center>
$\large{ \log((1 + \color{blue}{\frac{M}{2^{23}}}) \cdot \color{green}{2^{E-127}}) =  \log(1 + \color{blue}{\frac{M}{2^{23}}})} + \color{green}{E-127}$
</center>

<p>This may not seem that useful, but there&#39;s an important detail here: we&#39;re looking to <em>optimize</em> a program, not get exact results. So, a useful fact to note is that for $x$ between 0 and 1, $\log_2(1+x)\approx x$.</p>
<p><img src="/img/fast-sqrt/logx.png"></p>
<center style="color: #666;">
<p>We can simplify $\log_2(1+x)$ by approximating it as $x$.</p>
</center>

<p>We can get an <em>even better</em> approximation by slightly offseting our estimate; $\log_2(1+x)\approx x + \delta$ is a better approximation than $\log_2(1+x)\approx x$</p>
<p><img src="/img/fast-sqrt/betterlogx.png"></p>
<center style="color: #666;">
<p>We can approximate $\log_2(1+x)$ better with small shift.</p>
</center>

<p>It turns out the best value for $\delta = 0.0430357$ (as in minimizing the average error). By definition, our <span sytle="color:blue">mantissa</span> is between 0 and 1, so we can use this approximation ourselves.</p>
<center>
$\large{ \log(1 + \color{blue}{\frac{M}{2^{23}}}) + \color{green}{E-127} \approx  \color{blue}{\frac{M}{2^{23}}} + \delta + \color{green}{E-127}}$
</center>

<p>If we rearrange this a bit,</p>
<center>
$\large{\color{blue}{\frac{M}{2^{23}}} + \delta + \color{green}{E-127} = \color{blue}{\frac{1}{2^{23}}}(\color{green}{E} \cdot 2^{23} + \color{blue}{M}) + \delta \color{green}{- 127} }$
</center>

<p>Okay, why did we do any of this? This definitely is kinda random to not only take the $\log$ of our <code>float</code>, but also do all these approximations to then get rid of that $\log$ too? Why?</p>
<p>Look inside the parantheses in the above equation.</p>
<center>
$\large{\color{blue}{\frac{1}{2^{23}}}(\boxed{ \color{green}{E} \cdot 2^{23} + \color{blue}{M} }) + \delta \color{green}{- 127} }$
</center>

<!-- find better way to box/highlight^^^ -->
<p>That&#39;s precisely the bit representation of our <code>float</code>! So, in a way, the $\log$ of our number is equal to the bit representation of our <code>float</code>, up to some scaling and shifting.</p>
<center>
$\large{\log(\textrm{number}) \approx C(\texttt{bits}) + K}$
</center>

<p>With this under our belt, we can finally start looking at the steps of the fast inverse square root algorithm.</p>
<h2 id="evil-floating-point-bit-level-hacking">Evil Floating Point Bit Level Hacking</h2>
<p>First, we assign our number we want to find the inverse square root of into a <code>float</code> (a.k.a. scientific notation-type decimal number).</p>
<div style="background: #f8f8f8; overflow:auto;width:auto;border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em;"><pre style="margin: 0; line-height: 125%">      y  <span style="color: #666666">=</span> number;
</pre></div>

<p>Now, recall that a <code>float</code> isn&#39;t that compatible with bit shifting or that many operations, so here&#39;s the first clever part of the algorithm.</p>
<div style="background: #f8f8f8; overflow:auto;width:auto;border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em"><pre style="margin: 0; line-height: 125%">      i  <span style="color: #666666">=</span> <span style="color: #666666">*</span> ( <span style="color: #B00040">long</span> <span style="color: #666666">*</span> ) <span style="color: #666666">&amp;</span>y;<br></pre></div>

<p>What this does is we take the exact bits of our number as a <code>float</code> and copies it into a <code>long</code>. That&#39;s it. Under the hood, it takes the number at the memory address of <code>y</code> and exactly transfers the bits over to <code>i</code>. This will make our life easier here in the next step. </p>
<p>Since we have now put our number that we&#39;re trying to find the inverse square root to, <code>y</code>, as its bit representation, we have effectively stored approximately $\log({y})$ into <code>i</code>.</p>
<h2 id="what-the-f-k-">What the F#@k?</h2>
<p>The fabled step that makes this algorithm so smart.</p>
<div style="background: #f8f8f8; overflow:auto;width:auto;border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em;"><pre style="margin: 0; line-height: 125%">      i  <span style="color: #666666">=</span> <span style="color: #666666">0x5f3759df</span> <span style="color: #666666">-</span> ( i <span style="color: #666666">&gt;&gt;</span> <span style="color: #666666">1</span> );<br></pre></div>

<p>Remember, at the end of all of this, we want to find a number, $\alpha = \frac{1}{\sqrt{{y}}}$, but we have been working almost exclusively in logarithms. So, let&#39;s take the $\log$ of both sides.</p>
<center>
$\large{ \log(\alpha) = \log(\frac{1}{\sqrt{{y}}}) = \log({y}^{-\frac{1}{2}}) = -\frac{1}{2}\log({y}) \approx -\frac{1}{2}\texttt{i}}$
</center>

<p>Wait, but we have a division in there! On quite the contrary, it&#39;s a division by 2, and since <code>i</code> is a <code>long</code>, we can just bit shift to the right 1 to divide by 2! That&#39;s precisely what <code>i &gt;&gt; 1</code> does: it bit shifts <code>i</code> once to the right.</p>
<p>But what is the deal with that <code>0x5f3759df</code>? Well, remember that <code>i</code> is only an approximation for the $\log(y)$ up to some constants. So, we have to account for those constants <em>somehow</em>. Let&#39;s go back to $\alpha$. We know that</p>
<center>
$\large{ \log(\alpha) = -\frac{1}{2}\log({y})}$
</center>

<p>In terms of <code>float</code>s…</p>
<center>
$\large{ \log({(1 + \frac{\color{red}{M_{\alpha}}}{2^{23}}) \cdot 2^{\color{red}{E_{\alpha}}-127}}) = -\frac{1}{2}\log({(1 + \frac{\color{blue}{M_{y}}}{2^{23}}) \cdot 2^{\color{blue}{E_{y}}-127}})}$
</center>

<p>Fortunately we already know how to expand this from before.</p>
<center>
$\frac{1}{2^{23}}(\color{red}{E_\alpha \cdot 2^{23}} + \color{red}{M_\alpha}) + \delta - 127 = -\frac{1}{2}[\frac{1}{2^{23}}(\color{blue}{E_y \cdot 2^{23}} + \color{blue}{M_y}) + \delta - 127]$
</center>

<p>This looks pretty bad, but after some simplifying and rearranging…</p>
<center>
$\color{red}{E_\alpha \cdot 2^{23}} + \color{red}{M_\alpha} = \frac{3}{2}2^{23}(127 - \delta) - \frac{1}{2}(\color{blue}{E_y \cdot 2^{23}} + \color{blue}{M_y})$
</center>

<p>We know that anything of the form $E\cdot 2^{23} + M$ is just the bit representation of the number, and we know the bits of $y$ is just <code>i</code>, so</p>
<center>
$\color{red}{\alpha}_{\texttt{bits}} = \frac{3}{2}2^{23}(127 - \delta) - \frac{1}{2}\texttt{i}$
</center>

<p>That magic constant <code>0x5f3759df</code> is the hexadecimal (not totally sure why there is so many changes of bases) approximation of that constant $\frac{3}{2}2^{23}(127 - \delta)$. So what we do in this line of code is we bit shift <code>i</code> once to the right to halve it, and take that result and subtract it from <code>0x5f3759df</code> to correct for all the constants that came with our approximations of $\log(y)$. Not totally sure why the developers felt the need to write a variable for <code>threehalfs</code> and not this number, but what can we do.</p>
<p>But now note we are storing this value in <code>i</code>. So, from here on <code>i</code> no longer refers to the bits of $y$, but the bits of $\alpha$, our desired number. The bits, though, aren&#39;t particularly helpful since we want the <code>float</code> and decimal representation of $\alpha$, so we do just that:</p>
<div style="background: #f8f8f8; overflow:auto;width:auto;border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em;"><pre style="margin: 0; line-height: 125%">      y  <span style="color: #666666">=</span> <span style="color: #666666">*</span> ( <span style="color: #B00040">float</span> <span style="color: #666666">*</span> ) <span style="color: #666666">&amp;</span>i;
</pre></div>

<p>Just like how we casted the bits of a <code>float</code> $y$ into a <code>long i</code>, we now do the reverse and cast the bits of <code>i</code> into a <code>float</code> $y$.</p>
<p>At this point, we&#39;re technically done: $y$ currently stores an approximation of $\frac{1}{\sqrt{\texttt{number}}}$, using 0 steps of slow division! But we can do better for a marginal amount of extra computation.</p>
<h2 id="1st-iteration">1st Iteration</h2>
<p>Say we wanted to solve for the zeroes of the function</p>
<center>
$\large{f(y) = \frac{1}{y^2} - C}$
</center>

<p>where $C$ is any arbitrary constant. Solving for $y$…</p>
<center>
$\large{0 = \frac{1}{y^2} + C \rightarrow y = \frac{1}{\sqrt{C}}}$
</center>

<p>If we could find a way to approximate the roots of this function, we&#39;d then in turn have a way to approximate the inverse square root of any number!</p>
<p>In a <a href="https://xperimex.com/blog/fixed-points/#newton-raphson-method">previous post</a>, we discussed a technique to precisely do that: the Newton-Raphson Method (sometimes just called Newton&#39;s Method).</p>
<p>Let&#39;s say we have a random function $g(x)$. To find a solution, what can we do? Well, not a good idea, but <i>an</i> idea, we could just guess a random number $x_0$ as a solution. If $x_0$ is a solution, then obviously $g(x_0)=0$.</p>
<p><img src="/img/fast-sqrt/newton0.png"></p>
<center style="color: #666;">
<p>A pretty bad first guess.</p>
</center>

<p>As you&#39;d imagine, the chances of guessing a root of $g(x)$ immediately is slim. So, the next step in Newton&#39;s Method tells us to draw the <i>tangent line</i> at our first guess $(x_0, g(x_0))$ to get our next guess $x_1$.</p>
<p><img src="/img/fast-sqrt/newton1.png"></p>
<center style="color: #666;">
<p>A better, but still not ideal, approximation.</p>
</center>

<p><em>Now</em> we&#39;re getting pretty close. That&#39;s the whole premise of the Newton-Raphson Method:</p>
<ol>
<li>Pick an initial guess $x_n$</li>
<li>Draw the tangent line at $(x_n, g(x_n))$ and find where it intersects the $x$-axis</li>
<li>Use that as your new guess $x_{n+1}$</li>
<li>Repeat steps 1–3 as needed</li>
</ol>
<p>So, if we do another iteration of our example above…</p>
<p><img src="/img/fast-sqrt/newton2.png"></p>
<center style="color: #666;">
<p>Now we&#39;re getting to a reasonable estimation.</p>
</center>

<p>There are some edge cases though where this obviously won&#39;t work, such as if our guess happens to hit an extremum.</p>
<p><img src="/img/fast-sqrt/newtontangent.png"></p>
<center style="color: #666;">
<p>In this case, there&#39;s no additional guess since our tangent line is parallel to the axis.</p>
</center>

<p>We could even get loops where we just continuously bounce back and forth between two guesses. Fortunately, we don&#39;t have to worry about that. If our first guess is already really accurate and near the actual solution, then our graph $g(x)$ begins to look like this:</p>
<p><img src="/img/fast-sqrt/localLine.png"></p>
<center style="color: #666;">
<p>Up close, smooth, continuous graphs look linear.</p>
</center>

<p>$g(x)$ starts to look like a line! And when a function locally looks like a line, it also locally looks like its <em>tangent line</em>.</p>
<p><img src="/img/fast-sqrt/newtonFinal.png"></p>
<center style="color: #666;">
<p>Can&#39;t really beat that now.</p>
</center>

<p>This is important to us since we already have a good estimate from all of our bit manipulation from earlier, so we do one iteration of Newton&#39;s method to get an even <em>better</em> approximation.</p>
<p>To put this in terms of some equations to compute, we want to estimate the root of</p>
<center>
$\large{f(y) = \frac{1}{y^2} - C}$
</center>

<p>Given an initial guess $y_n$, our next guess $y_{n+1}$ is the solution to</p>
<center>
$\large{f&#39;(y_n)(y-y_n) + f(y_n) = 0}$
</center>

<p>since this describes where our tangent line generates our next solution. Solving for $y$ we get that</p>
<center>
$\large{y = y_{n+1} = y_n - \frac{f(y_n)}{f&#39;(y_n)}}$
</center>

<p>Now it&#39;s just a matter of plugging everything in.</p>
<center>
$\begin{align}
y_{n+1} &amp; = y_n - \frac{f(y_n)}{f&#39;(y_n)} \
\newline
&amp; = y_n - \frac{\frac{1}{y_{n}^2} - C}{-\frac{2}{y_{n}^3}} \
\newline
&amp; = \frac{3y_n - Cy_{n}^3}{2} \
\newline
&amp; = y_n(\frac{3}{2} - \frac{C}{2}y_{n}^2)
\end{align}$
</center>

<p>With a small substitution of $x_2 = \frac{C}{2}$,</p>
<center>
$\large{ y_{n+1} = y_n(\frac{3}{2} - x_{2}y_{n}^2) }$
</center>

<p>If we look at the line of code that entails this &quot;1st iteration&quot;,</p>
<div style="background: #f8f8f8; overflow:auto;width:auto;border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em;"><pre style="margin: 0; line-height: 125%">      y  <span style="color: #666666">=</span> y <span style="color: #666666">*</span> ( threehalfs <span style="color: #666666">-</span> ( x2 <span style="color: #666666">*</span> y <span style="color: #666666">*</span> y ) );
</pre></div>

<p>That&#39;s precisely the formula they have right there. You might wonder if that $\frac{3}{2}$ poses an issue at all in terms of division, but it is of no concern since we know its decimal expansion to be 1.5 so we can just use floating point arithmetic from the start; division becomes an increasingly hard problem when we <em>don&#39;t</em> know what the decimal representation of the quotient in question is.</p>
<h2 id="conclusion">Conclusion</h2>
<p>Let&#39;s quickly recap what we&#39;ve learned about the fast inverse square root algorithm and how it works:</p>
<div style="background: #f8f8f8; overflow:auto;width:auto;border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em; font-size: 12px"><pre style="margin: 0; line-height: 125%"><span style="color: #B00040">float</span> <span style="color: #0000FF">Q_rsqrt</span>( <span style="color: #B00040">float</span> number )
{
      <span style="color: #B00040">long</span> i;
      <span style="color: #B00040">float</span> x2, y;
      <span style="color: #008000; font-weight: bold">const</span> <span style="color: #B00040">float</span> threehalfs <span style="color: #666666">=</span> <span style="color: #666666">1.5F</span>;

      x2 <span style="color: #666666">=</span> number <span style="color: #666666">*</span> <span style="color: #666666">0.5F</span>;
      y  <span style="color: #666666">=</span> number;
      i  <span style="color: #666666">=</span> <span style="color: #666666">*</span> ( <span style="color: #B00040">long</span> <span style="color: #666666">*</span> ) <span style="color: #666666">&amp;</span>y;                     <span style="color: #408080; font-style: italic">// evil floating point bit level hacking</span>
      i  <span style="color: #666666">=</span> <span style="color: #666666">0x5f3759df</span> <span style="color: #666666">-</span> ( i <span style="color: #666666">&gt;&gt;</span> <span style="color: #666666">1</span> );             <span style="color: #408080; font-style: italic">// what the fuck? </span>
      y  <span style="color: #666666">=</span> <span style="color: #666666">*</span> ( <span style="color: #B00040">float</span> <span style="color: #666666">*</span> ) <span style="color: #666666">&amp;</span>i;
      y  <span style="color: #666666">=</span> y <span style="color: #666666">*</span> ( threehalfs <span style="color: #666666">-</span> ( x2 <span style="color: #666666">*</span> y <span style="color: #666666">*</span> y ) ); <span style="color: #408080; font-style: italic">// 1st iteration</span>
<span style="color: #408080; font-style: italic">//    y  = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed</span>

      <span style="color: #008000; font-weight: bold">return</span> y;
}
</pre></div>


<ol>
<li>We first take our number as a <code>float</code> $y$ and store its bits in a <code>long i</code>.</li>
<li>Noting that $\log_2(y) \approx \texttt{i}$, we approximate $\frac{1}{\sqrt{y}}$ using bit shifting and the magic number 0x5f3759df.</li>
<li>We then perform one iteration of Newton&#39;s method to get an even better approximation.</li>
</ol>
<p>These three steps required a fair bit of knowledge to properly unpack, but it&#39;s incredibly insightful when thinking about the lenghts programmers go to optimize their code. Remember: this is all to avoid using any division! What we consider such a simple operation is almost never such for a computer, and when it comes to teaching computers to do these things, they are as blind as a bat. But it&#39;s this difficulty and blank slate of a circuit board that makes computers be able to teach us, just as much as we teach them.</p>
]]></description>
         <link>http://xperimex.github.io/blog/fast-sqrt</link>
         <guid isPermaLink="true">http://xperimex.github.io/blog/fast-sqrt</guid>
         <dc:creator><![CDATA[Adi Mittal]]></dc:creator>
      </item>
      <item>
         <title><![CDATA[Pleasing Panoramas and Matrix Multiplication]]></title>
         <description><![CDATA[Capture the world as it (almost) is 

 <p>Out of all the apps on my phone, the camera is one that I can&#39;t see myself without anymore. Between being out with friends, or travelling with family, the camera rarely remains idle as I capture memories forever. Though, there is one particular feature of mobile photography I&#39;ve come to especially love: the panorama.</p>
<p><img src="/img/panorama-homography/grandCanyonEx.jpg"></p>
<center style="color: #666;">
<p>Even this struggles to capture how well the Grand Canyon lives up to its name.</p>
</center>

<p>Something about the extreme wide angle capturing more than what your eye can behold all at once makes it truly magical. And, if you have an Android phone, you can get even more incredible types of otherwise impossible photos with Google&#39;s staple Photo Spheres:</p>
<p><img src="/img/panorama-homography/PHOTOSPHERE.jpg"></p>
<center style="color: #666;">
<p>An &quot;unwrapped&quot; Photo Sphere; normally this would be an interactive literal sphere of the environment.</p>
</center>

<p>While these are cool, it does beg the question: how are these made? It&#39;s not like your phone is able to take them in a single snapshot; usually you have to spin or take multiple photos. How is your phone able to tie multiple images together into a single cohesive one? We&#39;ll explore a little bit of linear algebra to manipulate our photos exactly how we want to, and indulge in stylistic photos your others can only dream of.</p>
<h2 id="the-problem">The Problem</h2>
<p>Before anything else, let&#39;s first define what a panorama is. In computer graphics, a panorama is a type of <strong>mosaic</strong>, that is, a unification of two or more images. A panorama in particular, though, is a mosaic in which all the photos to be stitched together are all taken from the same camera position. When you take a panorama on your phone, all you&#39;re doing is spinning in place, so that&#39;s what we want to recreate.</p>
<!-- inset image -->
<p>So, if we&#39;re given two images from different angles, </p>
<p><img src="/img/panorama-homography/desk1.jpg">
<img src="/img/panorama-homography/desk2.jpg"></p>
<p>how do we combine them into a single unified image? Thinking about it this way is not super helpful, since, well, that&#39;s what we already know about panoramas. What do we want to get out of a panorama? If our panorama is done well, then objects in one image should overlap properly with the same objects in the other image.</p>
<p>For example, take a look at the top left of my computer monitor:</p>
<p><img src="/img/panorama-homography/desk1Corner.jpg">
<img src="/img/panorama-homography/desk2Corner.jpg"></p>
<p>In our panorama, these two points should overlap, since we obviously recognize these to be the same object in the real world. But to the two pictures, they are wildly different! In the first picture, the corner of my monitor is closer to the left side of the frame, while in the second picture, it is almost on the top-right edge of the image. So, if we try to manually align these two corners so that they overlap, we get:</p>
<p><img src="/img/panorama-homography/firstPanoAttempt.jpg"></p>
<p>While our single corner of the monitor is aligned between the two images, I don&#39;t think I have to try very hard to convince you that this isn&#39;t a great panorama. I mean, just look at the rest of the overlap.</p>
<p><img src="/img/panorama-homography/firstOverlap.jpg"></p>
<p>The skew angles of the resting laptop and the monitor itself don&#39;t align at all, and while my cable management is bad, it&#39;s not <em>that</em> bad. This is the real challenge at the heart of making panoramas: images are <em>flat</em>, while the motion of a panorama is <em>cylindrical</em>. Ideally we would take a &quot;cylindrical&quot; photo and unwrap that into a rectangle, but we can&#39;t. Undoubtedly, we will have to warp our images somehow to align.</p>
<p>How do we find the right way to warp our image? The first thing we will need to do is get more data! Having one point line up between the photos is not great, but, say, 10 different data points might not be bad.</p>
<p><img src="/img/panorama-homography/desk1labels.jpg">
<img src="/img/panorama-homography/desk2labels.jpg"></p>
<p>So, our final panorama would like the same numbered red and blue points to overlap. With data to use, the second thing we will need is a way to actually warp our image; how do we actually make our points between photos line up? For that, we turn to linear algebra.</p>
<h2 id="rethinking-coordinates">Rethinking Coordinates</h2>
<p>If you had a random ordinary point, how might you describe its position to someone?</p>
<p><img src="/img/panorama-homography/point.png"></p>
<center style="color: #666;">
<p>A lonely, solitary point living in the plane.</p>
</center>

<p>A common choice we&#39;re all familiar with in some way is by using a <strong>coordinate system</strong>. That is, we define a place to be $(0,0)$ and locate every point relative to that <strong>origin</strong> in terms of its $x$ and $y$ coordinates $(x,y)$.</p>
<p><img src="/img/panorama-homography/coordinateSpace.png"></p>
<center style="color: #666;">
<p>A still lonely, solitary point living in the plane, but with more lines.</p>
</center>

<p>In the above coordiante space choice, we might say the point is at $(3,2)$. But what exactly do we <em>mean</em> by the point being at $(3,2)$? What this really implies is that the point is 3 steps to the right of the origin, and 2 steps above the origin.</p>
<p><img src="/img/panorama-homography/basis.png"></p>
<p>So, instead of thinking of this point in terms of separate coordinates, we can think of it in terms of these two <strong>basis vectors</strong>. Let&#39;s use $\color{blue}{i}$ to represent the blue, horizontal vector, and $\color{red}{j}$ to represent the red, vertical vector. So, our point is really the combination of $\color{blue}{3i}$ and $\color{red}{2j}$, or simply, $\color{blue}{3i} + \color{red}{2j}$, which itself repsents another vector (the one pointing from the origin to the point $(3,2)$).</p>
<p>This might seem extra and unnecessary, since we just rewrote a vector as the sum of its horizontal and vertical components, which is what coordinates literally do in the first place. But the useful insight here is that there is nothing that says our basis vectors have to be in the unit directions! We can now rewrite points in multiple ways depending on our choice of $\color{blue}{i}$ and $\color{red}{j}$.</p>
<p><img src="/img/panorama-homography/basisNew.png"></p>
<center style="color: #666;">
<p>A new, quirky choice of basis vectors.</p>
</center>

<p>With a new choice of basis vectors, the vector $\color{blue}{3i} + \color{red}{2j}$ has a totally new position as that now encodes the coordinate $(5,3)$ since neither $\color{blue}{i}$ nor $\color{red}{j}$ represents horizontal or vertical steps anymore, but rather skew, diagonal steps. </p>
<p>But look at that! We&#39;ve basically accomplished our goal of warping points! We&#39;ve managed to transform the point $(3,2) \rightarrow (5,3)$ by manipulating $\color{blue}{i}$ and $\color{red}{j}$; both points are techincally at $\color{blue}{3i} + \color{red}{2j}$, just for different basis vectors.</p>
<p>This is what linear algebra and matrices encode geometrically. If we write our basis vectors $\color{blue}{i}$ and $\color{red}{j}$ in a matrix and multiply that by the vector representing our initial point, we will get a new point representing our transformation (a.k.a., our warp). How do we write our basis vectors in a matrix? Each vector implicitly has coordinates associated with themselves! In the above picture, $\color{blue}{i}$ points at $\color{blue}{(1,-1)}$, since from its tail to its tip it moves one step to the right and one step down. $\color{red}{j}$, on the other hand, points at $\color{red}{(1,3)}$, and these are precisely the vectors we see in our matrix.</p>
<p>For the unit basis vectors that point at $(1,0)$ and $(0,1)$, to differentiate them from any old pair of basis vectors, we call them $\color{blue}{\hat{\imath}}$ and $\color{red}{\hat{\jmath}}$ wearing a little hat, and their respective matrix the <em>identity matrix</em>, since it leaves vectors unchanged after multiplication (since that&#39;s what we used to define coordinates in the first place).</p>
<p><img src="/img/panorama-homography/matrixMult.png"></p>
<center style="color: #666;">
<p>The underlying idea of linear transformations.</p>
</center>

<p>These $2 \times 2$ matrices represent <em>linear transformations</em>. They&#39;re transformations in they way that they transform points from one coordinate to another (well, <a href="https://brilliant.org/wiki/eigenvalues-and-eigenvectors/">most of them at least</a>), and they are linear in the sense that keep all grid lines parallel, evenly spaced and, well, linear after the transformation. This is best seen through <a href="https://youtu.be/kYB8IZa5AuE?t=227">video</a> and not stills. For this post you don&#39;t need to understand the mechanics of matrix-vector multiplication, but just understand that it represents some transformation on a point.</p>
<h2 id="warping-images">Warping Images</h2>
<p>So why should we care? Why is this helpful in any way? If we think of each pixel on our images as a coordinate, we can just apply our transformation to all pixels on that image, find where they land and color them, and generate a new image. Let&#39;s take this picture as an example.</p>
<p><img src="/img/panorama-homography/canyon.jpg"></p>
<p>We can scale it, rotate it, or even shear it by applying the same transformation matrix to every pixel by changing $\color{blue}{i}$ and $\color{red}{j}$ like before.</p>
<p><img src="/img/panorama-homography/warpImage.jpg"></p>
<center style="color: #666;">
<p>An example transformation acting on our image.</p>
</center>

<p>But we have a <em>big</em> problem here: the typical linear transformation does not allow for translations. By the qualities of linear transformations, the origin cannot move, therefore forcing the bottom left corner of our images to always overlap! That&#39;s pretty restrictive in terms of the panoramas we can make—and for practical purposes—a complete nonstarter. If we want to continue through with making a panorama, we&#39;ll need to find a way around translations.</p>
<h3 id="homogenous-coordinates-and-affine-transformations">Homogenous Coordinates and Affine Transformations</h3>
<p>There&#39;s a very sneaky workaround being confined to the origin. To do so, we&#39;ll need to do something that might seem a bit weird to do translations. Let&#39;s rewrite our 2D points with a <em>3rd</em> coordinate. For a given $(x,y)$, let&#39;s rewrite that with a $z$-coordinate $(x,y,1)$. If $z \neq 1$, then we can just divide all the other coordinates by $z$ to make it equal to 1: $(x,y,w) \rightarrow (\frac{x}{w}, \frac{y}{w}, 1)$ (we generally use $w$ to represent the $z$-coordinate to indicate that there is no &quot;real&quot; $z$ value since everything is projected into 2D; we use $w$ as a &quot;weight&quot; to say how much we scale our projections down to). This means we have multiple coordinates represent the same point. In this way, $(2,5,1)$ and $(4,10,2)$ and $(-3,-7.5,-1.5)$ and $(2w,5w,w)$ all represent the same point (we don&#39;t include points when $z=0$ as it represents a point at infinity).</p>
<p>This might seem arbitrary, but what we&#39;re doing here is not too different than our original, 2-coordinate system. When we look at a cross-section of the $xyz$ coordinate space, it looks exactly like the $xy$ plane. What we are doing here is projecting all of $xyz$ space onto the plane $z=1$. </p>
<p><img src="/img/panorama-homography/homogeneousCoords.png"></p>
<center style="color: #666;">
<p>The geometry of projecting points onto $z=1$ is equivalent to drawing a line through the origin and the point, and finding where it intersects that plane.</p> 
</center>

<p>In fact, many of you are already familiar with <strong>homogeneous coordinates</strong> (representing 2D points with a 3rd scalar coordinate) and <strong>projective planes</strong>! When you take a photo on your phone, how does the camera know what&#39;s drawn in its frame? How does it take a 3-dimensional world and put it into a 2-dimensional picture? The many light rays that enter the camera lens (the origin) will intersect a plane ($z=1$) based on its focal length, and colors the pixel based on the projection.</p>
<p><img src="/img/panorama-homography/projectivePlane.png" style="width: 400px"></p>
<center style="color: #666;">
<p>A photo is homogeneous coordinates in disguise. While there&#39;s many sides to the building, our camera only cares about what it sees in front of it (a.k.a., what gets projected onto the frame). Our worldview is contained to a small projection.</p>
</center>

<p>Using this analogy with photos, clearly translations should be possible! If you&#39;ve seen any cat videos on the internet, clearly it is possible for the cat to enter and exit the frame freely without the camera necessarily moving, and that is precisely possible due to the fact the origin $(0,0,0)$ is not contained in our projective plane $z=1$, since all of our basis vectors have to stem out of the origin! (For those interested a translation matrix is equivalent to a shear along the $z$-axis.)</p>
<p>Think about what we&#39;re doing here: we&#39;re turning a linear transformation in 3-dimensions to create special non-linear <strong>affine transformations</strong> in 2-dimensions! When I first learned this geometrically, awe can&#39;t encapsulate the total shock I felt. So, if we&#39;re given a point $p$, we can transform it with a matrix $M$ to get its image $p&#39;$.</p>
<center>
$
Mp =
\begin{bmatrix}
a &amp; b &amp; c \\
d &amp; e &amp; f \\
g &amp; h &amp; i 
\end{bmatrix}
\begin{bmatrix}
x \\
y \\
1 
\end{bmatrix}
=
\begin{bmatrix}
wx&#39; \\
wy&#39; \\
w \\ 
\end{bmatrix}
=
\begin{bmatrix}
x&#39; \\
y&#39; \\
1 \\ 
\end{bmatrix}
$
</center>

<p>(Notice how $M$ is now a $3 \times 3$ matrix as we are working with 3D coordinates now) If our matrix-vector product results in a $w$ value not equal to 1, then we just divide everything by $w$ to make it so, and get our coordinate in terms of our 2D plane.</p>
<p>These projections with homogeneous coordinates are known as <strong>homographies</strong>. When we take one picture, and reproject it according to a matrix like this but <em>keeping the same camera center</em> (like the origin), we call it a homography. Again, like homogeneous coordinates, people have been leveraging homographies for a while now. You know how on roads, whenever there&#39;s text written like, &quot;STOP AHEAD&quot;, it&#39;s always a bit vertically stretched? That&#39;s because when you read it at the angle of a driver in a car, it looks more regular and readable. At least, that&#39;s my theory.</p>
<p>More creatively, that weird, perspective street art you might have seen before? That&#39;s the most manual you can get to using homographies—literally warping images with the angle you look at them to make them appear at a normal proportion.</p>
<p><img src="/img/panorama-homography/manual-homography.jpeg"></p>
<center style="color: #666;">
<p>Street artists have used the power of perspective for a long time.</p>
</center>

<p>What we&#39;re doing is computing a homography to build a <strong>mosaic</strong>. Just like the decorative tile art of the same name, we are taking tiles of photos that we transform to overlap, and them stitching them all together into one, broader image.</p>
<p>Moreover, our homographies have a really funny interpretation to them. Since we are reprojecting pictures, what it geometrically looks like is that we&#39;re taking two photos which should be rotated in space (as you would spin taking the panorama), and <em>taking a photo of the two photos</em>. Photo-ception.</p>
<p><img src="/img/panorama-homography/photoception.png"></p>
<center style="color: #666;">
<p>If you take a photo of two existing photos, you get one photo that unites the two together. If we can find out the right way to take the photo such that the overlap is correct, we get a panorama.</p>
</center>

<p>There are other ways to reproject images to make other mosaics with the own benefits and downsides, but this is what we&#39;ll use for now. Benefits with this type of mosaics? They are (relatively) easy and fast(er) to compute. Downsides? Since we are projecting onto a plane like this, we can only take panoramas up to 180° wide (can you see why?).</p>
<h2 id="one-slight-issue-">One Slight Issue…</h2>
<p>While it&#39;s great that we are able to transform points with matrices, let me remind us what our goal is.</p>
<p><img src="/img/panorama-homography/desk1labels.jpg">
<img src="/img/panorama-homography/desk2labels.jpg"></p>
<p>We have these two photos, where we want to transform one image&#39;s points to overlap with the other&#39;s. In terms of our matrix arithmetic from before, we have $p$ and $p&#39;$, but no matrix $M$... Up to this point we have been finding our image points using our own matrices, but how do we find that intermediate matrix given a point and its image?</p>
<h2 id="regressions-and-4-dimensional-lines">Regressions and 4-Dimensional Lines</h2>
<p>Like homogeneous coordinates, many of you will already be familiar with solving for the intermediate matrix given a $p$ and $p&#39;$. Let&#39;s do it with a simpler example.</p>
<p>If you had the points $(1,2)$ and $(6,4)$, and I needed you to find the line $y=mx+b$ that went through them, most of you would be able to do that. We&#39;d set up a system of linear equations</p>
<center>
$\begin{align}
2 &amp; = m(1) + b \
\newline
4 &amp; = m(6) + b
\end{align}$
</center>

<p>and solve for $m$ and $b$ respectively. In this case, $m=\frac{2}{5}$ and $b=\frac{8}{5}$. Simple algebra with little to worry about here. What is important to note here is that we <em>could</em> solve for a unique $m$ and $b$, since two points define one unique line.</p>
<p><img src="/img/panorama-homography/ordinaryLine.png"></p>
<center style="color: #666;">
<p>An ordinary line going between two points.</p>
</center>

<p>But what if I introduced a third point $(p_3,p_3&#39;)$? Or even a 4th point $(p_4,p_4&#39;)$? How do we draw a line through those 4 points? There might be a line that goes through all 4 points, but it&#39;s highly unlikely.</p>
<p><img src="/img/panorama-homography/linRegression.png"></p>
<center style="color: #666;">
<p>While there&#39;s no one line through all 4 points, what&#39;s the <em>closest</em> to a line we can get?</p>
</center>

<p>We may not have <em>exact</em> values for $m$ and $b$, but what&#39;s the best value for both to get the <em>closest</em> solution to this system of equations?</p>
<center>
$\begin{align}
p_1&#39; &amp; = m(p_1) + b \
\newline
p_2&#39; &amp; = m(p_2) + b \
\newline
p_3&#39; &amp; = m(p_3) + b \
\newline
p_4&#39; &amp; = m(p_4) + b
\end{align}$
</center>

<p>That&#39;s a task as simple as plugging it into a spreadsheet and doing a <strong>linear regression</strong>. More specifically, we can use the common <strong>least-squares regression</strong> where we want to minimize not the sum of the errors, but the sum of the square of the errors (as the name would suggest). For those a little more comfortable working with matrices and linear algebra, here&#39;s a <a href="#aside-least-squares-with-linear-algebra">more in-depth explanation</a> of what we&#39;re doing with our data when finding a regression.</p>
<p>To many, this might seem like an obvious thing to do; everyone from middle schoolers to office workers have been finding trend lines forever. But what we did here is pretty useful when we think more abstractly: given a system of linear equations that correlated independent data $p$ with their dependent data $p&#39;$, we were able to solve for the <strong>best coefficients of that system of linear equations</strong> that most closely solved the system (in the previous case was $m$ and $b$). Finding a line was a nice byproduct, but what we&#39;re really doing here is solving that system of linear equations.</p>
<p>Now I promise this will be helpful. Let&#39;s look at our original expanded matrix equation of $Mp = p&#39;$.</p>
<center>
$
\begin{bmatrix}
a &amp; b &amp; c \\
d &amp; e &amp; f \\
g &amp; h &amp; 1 
\end{bmatrix}
\begin{bmatrix}
x \\
y \\
1 
\end{bmatrix}
=
\begin{bmatrix}
wx&#39; \\
wy&#39; \\
w \\ 
\end{bmatrix}
$
</center>

<p>Remember, we&#39;re working in homogeneous coordinates, so $p&#39;$ might not land on the plane $z=1$, and we account for that with $w$ here. I also set $i=1$, since a) that corresponds with a certain scaling and is not necessarily unique vector in the land of homogeneous coordinates, and as a result, more importantly b) gives us one less variable to solve for.</p>
<p>Here, we will need to actually do the matrix-vector multiplication, and carrying it out nets a system of linear equations! (I know I said you won&#39;t need to know the mechanics of these operations, but it&#39;s hard to avoid it now. If you can accept this fact, that&#39;s great, but I&#39;d recommend looking <a href="https://youtu.be/XkY2DOUCWMU">here</a> if you are unfamiliar.) </p>
<center>
$\begin{align}
ax + by + c &amp; = wx&#39; \
\newline
dx + ey + f &amp; = wy&#39; \ 
\newline
gx + hy + 1 &amp; = w
\end{align}$
</center>

<p>Using the third equation in tandem with the first two…</p>
<center>
$\begin{align}
ax + by + c &amp; = (gx + hy + 1)x&#39; \
\newline
dx + ey + f &amp; = (gx + hy + 1)y&#39; 
\end{align}$
</center>

<p>Just like before, we can solve for $a$, $b$, $c$, $d$, $e$, $f$, $g$, and $h$ with a least-squares regression! Since we have 8 variables, at minimum we need 8 equations, or 4 pairs of $p$ and $p&#39;$ (since each pair contains two equations: one for $x&#39;$ and one for $y&#39;$). Though, just like we have 10 points, generally it is better to have more data and overfit than less (we&#39;d rather have an overall average fit, than just 4 points be <em>exatly</em> where we want them to be). It&#39;s weird to think of this geometrically, since what we&#39;re doing here is not finding the line between one independent variable and one dependent variable, but rather <em>two</em> independent variables $(x,y)$ with <em>two</em> corresponding dependent variables $(x&#39;,y&#39;)$; our regression exists in 4-dimensions!</p>
<h2 id="putting-it-all-together">Putting It All Together</h2>
<p>Let&#39;s quickly reflect on what we&#39;ve covered thus far.</p>
<ol>
<li>We&#39;ve redefined coordinates purely with vectors, allowing us to nicely compact our image-warping transformations in matrices.</li>
<li>Our original definition of coordinates failed to include translations—a key transformation. We described 2-dimensional points in 3-dimensions with homogeneous coordinates, resolving our worries.</li>
<li>We then ran into ANOTHER problem in that while we knew how to warp images <em>given</em> the transformation matrix, we really wanted to be able to find the matrix given a starting point and an end point to map to.</li>
<li>Using a least-squares regression, we were able to turn our unknown matrix equation into a system of linear equations that were much easier to work with to compute our homography (sort of, see the <a href="#aside-least-squares-with-linear-algebra">aside</a> below).</li>
</ol>
<p>Let&#39;s use this first photo to give our list of points $p$.</p>
<p><img src="/img/panorama-homography/desk1labels.jpg"></p>
<p>And we&#39;ll try to match those red points to these blue points on the second photo: our list of $p&#39;$.</p>
<p><img src="/img/panorama-homography/desk2labels.jpg"></p>
<p>Having the computer compute the transformation matrix, we take that matrix and multiply every pixel (remember, treating them as coordinates/vectors), and warping the first image. Then, we can overlay them to see how close our points line up! If our points were well selected, and our computed homography—with the least-squares regression—has minimal error, we should get a pretty decent attempt at a panorama.</p>
<p><img src="/img/panorama-homography/firstPano.jpg"></p>
<p>Sure, the blending isn&#39;t great, and it didn&#39;t <em>completely</em> fix the overlap issue, but the seams and photo stitching definitely is much nicer! And honestly, it&#39;s pretty cool seeing how the image was transformed and finding the outline of the images cross like that.</p>
<p><img src="/img/panorama-homography/firstPanoOutline.jpg"></p>
<p>With some simple masking and basic filtering (basically averaging every pixel&#39;s color with the pixels around it), suddenly it really begins to look clean.</p>
<p><img src="/img/panorama-homography/panorama.jpg"></p>
<p>While this is cool, it does reveal another unfortunate downside of our choice of mosaic: if we want a uniform picture, we have to sacrifice a lot of data. </p>
<p><img src="/img/panorama-homography/panoramaCrop.jpg"></p>
<p>Even so, it doesn&#39;t even look that bad. All in all, though, not a bad first attempt at building a panorama.</p>
<h2 id="what-next-">What Next?</h2>
<p>While we have a working prototype, we can do signficantly better. For one, I used only 10 labelled points to compute our homography, but if you use even more, it&#39;s not hard to get a better, and closer fit. With algorithms like <a href="https://zju3dv.github.io/loftr/">LoFTR</a>, finding lots of corresponding labelled points between multiple images is quick and easy.</p>
<center>
<video width="85%" playsinline="" autoplay="autoplay" loop="loop" preload="" muted="">
      <source src="/img/panorama-homography/loftr-homepage-demo.mp4" type="video/mp4">
</center>
<center style="color: #666;">
<p>Some really smart people made an algorithm specifically to finding high quality object matching between multiple photos. Credit: LoFTR Team</p>
</center>

<p>Also, since we are manually constructing our panorama, we can stitch and blend photos that have no right being together in a panorama.</p>
<p><img src="/img/panorama-homography/lightdark2.jpg"></p>
<center style="color: #666;">
<p>Going from a well-lit to a dark photo makes for some artsy renditions (even more if you blend it a little nicer).</p>
</center>

<p>In a similar manner, we only conjoined two photos together, but we can easily extend this to as many photos as we want (but I can&#39;t say how well the photos towards the end will necessarily stretch).</p>
<p>We never really touched on our homographies, either. When we decided 10 initial points $p$ and 10 warped points $p&#39;$, our $p&#39;$ was decided as a result of lining up 2 photos. What if we didn&#39;t want to line up multiple photos, but rather just creatively warp a single photo? </p>
<p><img src="/img/panorama-homography/rectification.jpeg"></p>
<center style="color: #666;">
<p>Something not quite lined up? A simple homography can fix that for us.</p>
</center>

<p>This is know as <strong>rectification</strong>, as it is a means to correct for mistakes we might have had in our photo.</p>
<p>Finally, the last improvement we can make to our mosaics is trying new projections and warpings. If we want something even as simple as just wider, up to 360°, full views, we&#39;ll need to find something more robust than our previous approach. Or what if we wanted to make something akin to a full photosphere like from before?</p>
<p><img src="/img/panorama-homography/PHOTOSPHERE.jpg"></p>
<p>What we did today was simply <strong>planar projection</strong>, or just reprojection onto a plane. We did that with homogenous coordinates. For wider, more complete mosaics, we&#39;ll need either <strong>cylindrical</strong> or <strong>spherical projection</strong>, which is exactly what it sounds like. These have their own benefits like wider field of view, but because of the nature of projecting onto a curved surface, the images being stitched together do tend to, well, curve. The type of mosaic one uses comes down to preference and artistic need. </p>
<p>And lastly, there are many optimizations and polishing details we could add to make our panoramas cleaner, and run faster. For instance, we never mentioned the discontinuities that could be present in warping our images with matrix multiplication. While linear transformations keep lines before the warp as lines afterwards as well, that&#39;s only helpful if our line is <em>continuous</em>. Pictures are <em>not</em> continuous! They are discrete points! So, <strong>forward warping</strong> with our matrix multiplication and finding where pixels lands can sometimes create (albeit, usually imperceptible) holes in our images, but they are there nonetheless. Instead, we can <strong>reverse warp</strong> by applying the inverse of our transformation matrix, and find what coordinates land on our original image! Not to mention different blending and masking techniques, or even just algorithmic improvements to make the code run faster. Check out the Python notebook below for more details.</p>
<p>For more like this and additional resources, I recommend reading these <a href="https://inst.eecs.berkeley.edu/~cs194-26/fa21/Lectures/MoreMosaics.pdf">slides from UC Berkeley</a>&#39;s introductory computer vision and computational photography class.</p>
<p>I hope this gave an interesting peak at the intersection of linear algebra and photography, and more over, I hope this gave you an appreciation for the math your phone goes through every time you take a panorama. </p>
<p>If you&#39;re interested, here&#39;s a link to a <a href="https://colab.research.google.com/drive/1bgOaBnHTlKx-DYfLg2HmtsaFekWgwJFn?usp=sharing">Python notebook</a> where you can see some of my experiments during my struggle and exploration with panoramas and homographies.</p>
<hr>
<h2 id="aside-least-squares-with-linear-algebra">Aside: Least-Squares with Linear Algebra</h2>
<p>Okay, this previous section is really hard to describe without already knowing a fair amount of linear algebra, and it felt a little flat without having a more methodical procedure of solving a least-squares regression. I wasn&#39;t planning on including this section, but it felt incomplete otherwise. For those interested, feel free to peer over it, but this is not necessary within the scope of this post; all you need to understand is what our regression is accomplishing, thinking of that &quot;line of best fit&quot; idea giving rise to optimal coefficients in a overfitted system of linear equations.</p>
<p>Let&#39;s go back to when we were trying to find a line between two points. If you have 2 points, $(p_1, p_1&#39;)$ and $(p_2, p_2&#39;)$ being fit to the line $y=mx+b$, we have a system of linear equations like before.</p>
<center>
$\begin{align}
p_1&#39; &amp; = m(p_1) + b \
\newline
p_2&#39; &amp; = m(p_2) + b
\end{align}$
</center>

<p>We can solve this just like we did before to find $m$ and $b$, but there&#39;s another, sly way we can approach this. If we look carefully at the structure of these equations, there&#39;s actually a secret matrix relationship embedded into this system. </p>
<center>
$
\begin{bmatrix}
p_1&#39; \\
p_2&#39;
\end{bmatrix}
=
\begin{bmatrix}
p_1 &amp; 1 \\
p_2 &amp; 1
\end{bmatrix}
\begin{bmatrix}
m \\
b
\end{bmatrix}$
</center>

<p>In a sense, that&#39;s what a matrix is: a system of linear equations, and you can freely go between either a system of linear equations or a matrix via matrix multiplication. (I know I said you won&#39;t need to know the mechanics of these operations, but it&#39;s hard to avoid it now. If you can accept this fact, that&#39;s great, but I&#39;d recommend looking <a href="https://youtu.be/XkY2DOUCWMU">here</a> for more details.)</p>
<p>If we write this in general terms, we are basically solving the equation</p>
<center>
$b = Ax$
</center>

<p>where $A$ is a matrix, and $b$ and $x$ are vectors, and we are solving for the latter. It might seem pointless to rewrite it, but what we&#39;re actually solving is</p>
<center>
$Ax - b = 0$
</center>

<p>Since $Ax$ is <em>exactly</em> equal to $b$ in the 2-point case, we can solve this matrix equation fairly directly; when there&#39;s a unique, perfect solution $Ax$ is the same vector as to $b$. We were able to find a unique line with $m$ and $b$ through them, no? Just as we were able to solve the system of linear equations before, we can easily solve this with matrix inverses:</p>
<center>
$A^{-1}b = x$
</center>

<p>Now, let&#39;s add more points.</p>
<center>
$\begin{align}
p_1&#39; &amp; = m(p_1) + b \
\newline
p_2&#39; &amp; = m(p_2) + b \
\newline
p_3&#39; &amp; = m(p_3) + b \
\newline
p_4&#39; &amp; = m(p_4) + b
\end{align}$
</center>

<p>Now we turn this into a matrix equation like before.</p>
<center>
$
\begin{bmatrix}
p_1&#39; \\
p_2&#39; \\
p_3&#39; \\
p_4
\end{bmatrix}
=
\begin{bmatrix}
p_1 &amp; 1 \\
p_2 &amp; 1 \\
p_3 &amp; 1 \\
p_4 &amp; 1
\end{bmatrix}
\begin{bmatrix}
m \\
b
\end{bmatrix}$
</center>

<p>We know that there&#39;s a good chance our four points don&#39;t all lie on the same line. So it&#39;s unlikely that $Ax - b = 0$. Moreover, now that our matrix $A$ isn&#39;t square, we can&#39;t just use inverses to solve for $x$. So instead, we want to get a line that gets <em>as close</em> to 0 (a.k.a. being a perfect fit). So our goal is to </p>
<center>
$\min||Ax-b||^2_2$
</center>

<p>Here, the $||x||_2$ means we&#39;re looking at the Euclidean distance (a.k.a. straight line distance) as our error for our line of best fit, and we&#39;re squaring it to get a tighter fit since small errors are kept relatively small, while large errors are weighed heavier. We know $A$ and $b$ with $x$ as our unknown—this sort of looks like a parabola-y equation! When we minimize a single variable function, we do so with the derivative. We can do the same thing here except with the multivariable equivalent: the gradient. So, we know the minimum occurs where the gradient of this function is 0.</p>
<center>
$\nabla_{x}||Ax-b||^2_2 = 0$
</center>

<p>Even if you&#39;re not familiar with multivariable calculus, much of the following should still look vaguely familiar to the chain and power rules of single-variable calculus.</p>
<center>
$\begin{align}
\nabla_{x}||Ax-b||^2_2 &amp; = 0 \
\newline
2A^T(Ax-b) &amp; = 0 \
\newline
2A^TAx - 2A^Tb &amp; = 0 \
\newline
A^TAx &amp; = A^Tb
\end{align}$
</center>

<p>All finally simplifying to the very nice formula of</p>
<center>
$x = (A^TA)^{-1}A^Tb$
</center>

<p>I like this approach for it&#39;s intuitive roots in the geometry of single-variable calculus, but if you want a more strictly linear algebra approach, here&#39;s this excerpt from <a href="https://textbooks.math.gatech.edu/ila/least-squares.html">Georgia Tech</a> that explains another proof for the same formula:</p>
<hr>
<p><strong>Theorem.</strong> Let $A$ be a $m \times n$ matrix and let $b$ be a vector in $\mathbb{R}^m$. The following are equivalent:</p>
<ol>
<li>$Ax=b$ has a unique least-squares solution.</li>
<li>The columns of $A$ are linearly independent.</li>
<li>$A^TA$ is invertible.</li>
</ol>
<p>In this case, the least-squares solution is</p>
<center>
$x = (A^{T}A)^{-1}A^{T}b$
</center>

<p><strong>Proof.</strong> The set of least-squares solutions of $Ax = b$ is the solution set of the consistent equation $A^TAx = A^Tb$, which is a translate of the solution set of the homogeneous equation $A^TAx = 0$. Since $A^TAx$ is a square matrix, the equivalence of [facts] 1 and 3 follows from the invertible matrix theorem. The set of least squares-solutions is also the solution set of the consistent equation $Ax=b_{\textrm{Col}(A)}$, which has a unique solution if and only if the columns of A are linearly independent. </p>
<hr>
<p>Basically, it says if our system of linear equations contain only unique equations (i.e. no one equation is a multiple of another), we can turn our non-square matrix $A$ into a square one by multiplying by its transpose $A^T$, and solve our least squares the way we&#39;d solve it before with inverses. In other words, if our matrix follows the criteria listed above, our minimizing solution comes from creating an equivalent equation with an invertible matrix:</p>
<center>
$\begin{align}
Ax &amp; = b \
\newline
A^TAx &amp; = A^Tb \
\newline
(A^TA)^{-1}A^TAx &amp; = (A^TA)^{-1}A^Tb \
\newline
x &amp; = (A^TA)^{-1}A^Tb
\end{align}$
</center>

<p>Netting precisely the same formula as before.</p>
<p>Now, let&#39;s recall the our matrix equation from before of the homography we wanted to solve. </p>
<center>
$
\begin{bmatrix}
a &amp; b &amp; c \\
d &amp; e &amp; f \\
g &amp; h &amp; 1 
\end{bmatrix}
\begin{bmatrix}
x \\
y \\
1 
\end{bmatrix}
=
\begin{bmatrix}
wx&#39; \\
wy&#39; \\
w \\ 
\end{bmatrix}
$
</center>

<p>Then, we expanded this into 3 linear equations, and further simplified them to the following two:</p>
<center>
$\begin{align}
ax + by + c &amp; = (gx + hy + 1)x&#39; \
\newline
dx + ey + f &amp; = (gx + hy + 1)y&#39; 
\end{align}$
</center>

<p>This, can be rewritten as another, secret matrix equation:</p>
<center>
$
\begin{bmatrix}
x &amp; y &amp; 1 &amp; 0 &amp; 0 &amp; 0 &amp; -x&#39; \cdot x &amp; -x&#39; \cdot y \\
0 &amp; 0 &amp; 0 &amp; x &amp; y &amp; 1 &amp; -y&#39; \cdot x &amp; -y&#39; \cdot y
\end{bmatrix}
\begin{bmatrix}
a \\
b \\
c \\
d \\
e \\
f \\
g \\
h 
\end{bmatrix}
=
\begin{bmatrix}
x&#39; \\
y&#39;
\end{bmatrix}
$
</center>

<p>Wait, we turned our original matrix equation into another one? As awful as that may look, this is much more useful than our original equation since now, all of our unknowns are in a vector instead of a matrix; it really is no different than our previous least-squares examples, and we&#39;re still solving for the vector $x$ in</p>
<center>
$Ax = b$
</center>

<p>So, we can still solve it like before finding </p>
<center>
$x = (A^{T}A)^{-1}A^{T}b$
</center>

<p>And with that, we now have also gone through what our program is doing under the hood, and have gone through some of the tedium of justifying what a least-squares regression is from a linear algebra perspective.</p>
]]></description>
         <link>http://xperimex.github.io/blog/panorama-homography</link>
         <guid isPermaLink="true">http://xperimex.github.io/blog/panorama-homography</guid>
         <dc:creator><![CDATA[Adi Mittal]]></dc:creator>
      </item>
      <item>
         <title><![CDATA[Constructive Proofs and Careful Practices]]></title>
         <description><![CDATA[Is this really math anymore? 

 <p>Many who have dipped their toes in math for even a little bit will know that $\sqrt{2}$ is irrational. Like many other well known mathematical constants like $\pi$ and $e$, $\sqrt{2}$ can&#39;t be written out as a fraction, and its decimal expansion goes on forever without repeating. It&#39;s a novel fact, and comes with a fairly simple proof too.</p>
<p><strong>Claim: $\sqrt{2}$ is irrational.</strong></p>
<p><strong>Proof:</strong> Suppose that $\sqrt{2}$ is not irrational. Therefore it is rational, and can be written as $\sqrt{2} = \frac{p}{q}$ where $p$ and $q$ are distinct coprime numbers (i.e. they don&#39;t share any factors in common; this is a way of sayiing that there is a unique way of writing $\sqrt{2}$ as a fraction in <em>lowest terms</em>). Squaring both sides and moving terms around, this equation becomes $2q^2 = p^2$. Therefore, $p^2$ is even, since it will always have a factor of 2 according to the lefthand-side of the equation. If $p^2$ is even, then $p$ is also even (if you&#39;re unsure of this fact, try some test cases and proving it!). Since $p$ is even, then let&#39;s rewrite it as $p=2n$. Plugging this into our equation yields: $2q^2 = p^2 = (2n)^2 = 4n^2$. Dividing both sides by 2 gives us $q^2 = 2n^2$. Similar to before, the equation implies that $q^2$ and hence $q$ is even due to that factor of 2 on the righthand-side. But this is a contradiction! $p$ and $q$ cannot simultaneously both be coprime and even (share a factor of 2). Hence, our initial assumption that the $\sqrt{2}$ is rational is wrong, and allows us to conclude that $\sqrt{2}$ is irrational. $\blacksquare$</p>
<p>It&#39;s not a long proof at all, and in the grand scheme of the history of math, pretty important, too. Supposedly, this was the first instance of irrationality being proven as a possible quality. More specifically, <a href="https://mathworld.wolfram.com/PythagorassConstant.html">legend</a> has it that Hippasus of Metapontum was credited with showing that the $\sqrt{2}$ is <em>not rational</em> (note the word choice) in the 5th century BCE while at sea, and upon sharing his amazing discovery, was instantly thrown overboard and left to drown. </p>
<p>Arguably of more significance, the proof highlights a general technique we use not just in math, but everyday logic and reasoning: <strong>proof by contradiction</strong>. </p>
<h2 id="proof-by-contradiction">Proof by Contradiction</h2>
<p>I&#39;m sure you have all heard someone say, &quot;For the sake of argument…,&quot; at some point in your life before. The idea is to disprove any hypothetical argument by showing it leads to an impossibility. </p>
<p>Let&#39;s say someone was arguing that Euclid was still alive today. Instead of remaining in utter shock at such a claim, here&#39;s a simple reply to show otherwise. For the sake of argument, let&#39;s assume Euclid <i>is</i> still alive. It is generall agreed that Euclid lived around 300 BCE, so if he is alive now, that would make him around 2300 years old now, which is crazy! Only a handful of people live past 100, let alone 1000 years. So it is safe to say, it is not the case that Euclid is still alive today.</p>
<p>In fact, the Latin phrase that describes proof by contradiction, &quot;Reductio ad absurdum,&quot; literally means, &quot;Reduced to the absurd/impossible&quot;.</p>
<p>Even if you haven&#39;t realized it before, you&#39;ve probably used this same principle a lot in school. When taking a test, process of elimination can be an immensely helpful tactic to find the right answer to a question: if you can eliminate what you definitely know to be <em>false</em>, the rest of the options must include the <em>truth</em>.</p>
<p>At its core, we&#39;re using double negatives to prove a &quot;positive&quot; statement; we assume something to be false, show that it can&#39;t be, and therefore conclude, it&#39;s true since something that is not false must be true. If a number is not rational, it&#39;s irrational. If someone is not alive, they&#39;re dead. If someone&#39;s not guilty, they&#39;re innocent.</p>
<p>That last one feels weird, right? Just because there&#39;s no evidence to show someone is involved in a crime does not mean we always feel them to have been completely removed, right? In the previous examples, there&#39;s a strong sense of <strong>complements</strong>. &quot;Rational&quot; means &quot;not irrational&quot;, so &quot;not not irrational&quot; is the same as &quot;irrational&quot;. &quot;Alive&quot; and &quot;not dead&quot; are the same, so &quot;not alive&quot; is &quot;not not dead&quot; is &quot;dead&quot;. But is &quot;not guilty&quot; really the same as &quot;innocent&quot;? Semantically, that&#39;s what it means. If you Google it, that&#39;s what you get. </p>
<p><img src="/img/constructive-proofs/notGuilty.png"></p>
<center style="color: #666;">
<p>Of course, Google never lies.</p>
</center>

<p>From a casual, conversational point, it might, but from a legal standpoint, there&#39;s a reason why we make a distinction. We don&#39;t live in a binary world. So, it&#39;s not totally clear that we can say &quot;not guilty&quot; is the same as &quot;innocent&quot;, <em>even if that&#39;s what their definitions may mean</em>. Even if two things are definitionally polar opposites, we, as the humans behind the words&#39; significance to begin with, add subtlety and nuance. </p>
<p>&quot;Not guilty&quot; still insinuates that there&#39;s a feeling that there&#39;s something missing; we think they are guilty, but are unable to prove it. So even if we define &quot;guilty&quot; to be &quot;not innocent&quot;, we might not want to say &quot;not guilty&quot; is the same as &quot;innocent&quot;.</p>
<p>Which should come with a weird realization: if &quot;guilty&quot; is &quot;not innocent&quot;, then &quot;not guilty&quot; is &quot;not not innocent&quot;, which we said to not be equal to &quot;innocent&quot;. <strong>Double negatives don&#39;t always cancel out.</strong></p>
<p>Maybe our original definitions are wrong then? But it would be hard to define either &quot;guilty&quot; or &quot;innocent&quot; external to each other.</p>
<p>This may just seem like nitpicking, but it&#39;s important to consider this, since it puts into doubt such an intuitive, clear cut idea. If we can&#39;t use double negatives in one place, who&#39;s to say where else we can&#39;t use it? It might seem obvious at first that &quot;not alive&quot; must mean &quot;dead&quot;, but have we really <em>shown</em> that? Just because it&#39;s absurd to think about Euclid being alive right now, does our proof really <em>guarantee</em> that? Is there something more to rational and irrational numbers that we might be missing? Just like with differentiating &quot;not guilty&quot; and &quot;innocent&quot;, just because we have not been able to show someone guilty does not mean that they aren&#39;t.</p>
<p>Yet, <strong>this is precisely the concept that proof by contradiction relies on</strong>. We assume the opposite of what we actually want to prove, show it is impossible, then negate it to get to our original statement. But we don&#39;t <em>actually</em> show anything directly about our claim, only that it is impossible that it <em>can&#39;t</em> be true. If that&#39;s not valid—like it is the case between &quot;guilty&quot; and &quot;innocent&quot;—this no longer becomes a valid proof technique! </p>
<p>Above, we&#39;ve only demonstrated that $\sqrt{2}$ is not rational, when we wanted to show that it is irrational. Did we really do that?</p>
<h2 id="the-law-of-excluded-middle">The Law of Excluded Middle</h2>
<p>The easy answer to that is yes. We state a strict definition, and we can pretty clearly figure out when something is binary and when something has wiggle room. We can define a number to either strictly be rational or irrational. If it&#39;s not one, it has to be the other.</p>
<p>Technically, fine, yeah, we can do that. But that&#39;s kind of unsatisfying. But, there&#39;s a more fundamental question we should ask, since we&#39;re not just concerned with a number being rational or not, or someone&#39;s mortality, but proofs in general; we want to know if we can use proof by contradiction consistently. In general, we&#39;re trying to prove the <em>truth</em> of claims, so what we really care about is the following question: if something is not true, is it false (and vice versa)?</p>
<p>Again, obviously yeah, right? What else could it be? All <strong>declarative sentences</strong> (sentences make a claim about something, i.e. not questions) have to be true or false. It&#39;s that simple. It either is or it isn&#39;t. &quot;Cats are animals,&quot; is true, and, &quot;The Earth is flat,&quot; is false. Easy. </p>
<p>This is known as the <strong>Law of Excluded Middle</strong>, for, well, we exclude any type of middle value in between true or false. For those who like their logical formalities, if $\Phi$ is our claim about the world, then we say $(\Phi \lor \neg \Phi)$ is a <strong>tautology</strong> (that is, something that is always true). In natural language, this literally means &quot;either our claim of the world is true or our claim of the world is not true&quot;, which just makes sense. </p>
<hr>
<p>This forms one of the, and I can&#39;t make this up, <strong>Three Laws of Thought</strong> upon which &quot;reasonable arguments&quot; are based off of. These principles include:</p>
<ol>
<li>The Law of Excluded Middle: every claim or its negation is true.</li>
<li>The Law of Non-Contradiction: nothing can simultaneously be true and false.</li>
<li>The Law of Identity: everything is identical to itself.</li>
</ol>
<p>These three are usually taken as &quot;common sense&quot; axioms, and along with a few other assumptions build the basis of inference and deduction. Some might note that the first two laws might mirror each other through <a href="https://brilliant.org/wiki/de-morgans-laws/">De Morgan&#39;s laws</a>, but remember these don&#39;t actually explicitly state De Morgan&#39;s laws and we have no way of inferring that with these three principles alone. These three laws come up in many contexts, and have been refomalized many times over across history. Even the last Law of Identity, which seems almost pointless, has been taken by none other than Leibniz (yes, the same one from calculus) and been turned into <a href="https://plato.stanford.edu/entries/identity-indiscernible/">two laws</a>. That&#39;s for another day, though, and we will continue to only focus on the first law.</p>
<hr>
<p>Ok, then how about the following claim?</p>
<center>
<p style="font-size: 30px"><i>This sentence is false.</i></p>
</center>

<p>Is this true or false? If it&#39;s true, then it declares itself to be false. If it&#39;s false, then it must be giving the wrong information, and therefore it actually is declaring itself to be true. And if it&#39;s true…</p>
<p>Suddenly binary truth values don&#39;t seem to be as reliable as they first seemed. This sentence doesn&#39;t neatly fit into one cateogry. If you consider one side, it flips to the other. It&#39;s been aptly named the Liar&#39;s paradox for its deceptive nature, and there are many <a href="https://en.wikipedia.org/wiki/Liar_paradox#Possible_resolutions">attempted solutions</a>, of my favorites being the <a href="https://plato.stanford.edu/entries/logic-fuzzy/">fuzzy logic</a> answer for its clarity and funny name. The number of attempts at resolving such an annoying sentence, though, should highlight that binary truth values are not always the right approach.</p>
<!-- Talk about law of excluded middle -->
<p>At this point, it&#39;s time we might have to reconsider the Law of Excluded Middle. Maybe this is just a dumb paradox that should be ignored as an edge case, but if you leave it as it is, then are we really going to be happy with what we have, knowing that there are some problems out there we just can&#39;t address?</p>
<h2 id="intuitionism">Intuitionism</h2>
<p>Perhaps, we don&#39;t have to reject the Law of Excluded Middle, but instead come up with a <em>stronger</em> type of reasoning. As we saw, the Law of Excluded Middle lines up pretty well with most things we observe in general, so we shouldn&#39;t discount it for that. Though, we might find a way that can avoid this issue we ran into with &quot;not guilty&quot; versus &quot;innocent&quot; altogether, and that would be foolproof from the start. </p>
<p>Our proof by contradiction is known as a <strong>non-constructive proof</strong>, in that it reasons about a claim without ever <em>demonstrating</em> the claim itself; there&#39;s no actual evidence presented for the thing we want to show true, since we try to make it appear &quot;obvious&quot; that there is no other way for such a claim to exist. </p>
<hr>
<p>Our proof by contradiction for $\sqrt{2}$ being irrational is one example, but here&#39;s another one of my favorites.</p>
<p><strong>Claim: There exists irrational numbers $a$ and $b$ such that $a^b$ is rational.</strong></p>
<p><strong>Proof:</strong> We know (and continue later to show) that $\sqrt{2}$ is irrational, so consider the number $\sqrt{2}^\sqrt{2}$. If this is rational, we&#39;re done. If this is irrational, then consider the number $(\sqrt{2}^\sqrt{2})^\sqrt{2} = \sqrt{2}^2 = 2$, which is rational, and hence we are done.</p>
<p>Never once did we actually deduce the rationality of $\sqrt{2}^\sqrt{2}$, but by exhausting the possible cases, it doesn&#39;t matter since every possibility leads to a conclusion that proves our claim.</p>
<hr>
<p>If we can find a <strong>constructive proof</strong> and actually manifest our claim in some way, then we don&#39;t have to worry about double negatives or anything like that since we directly showed what we wanted to.</p>
<p>We&#39;re now dabbling along lines of <strong>intuitionistic logic</strong> where, ironically, we are breaking our natural sense of double negation and relying solely on these constructive proofs to validate truths. Since, in a way, non-constructive proofs are just left in abstraction and are no more than just a construct of our mind. Intuitionism tries to separate ourselves in the proof by showing an objective way of realizing a truth.</p>
<p>Let&#39;s go back to our original proof by contradiction above:</p>
<p><strong>Claim: $\sqrt{2}$ is irrational.</strong></p>
<p>Remember, we don&#39;t trust double negatives, so we want to avoid saying &quot;irrational&quot; is the same as &quot;not rational&quot;. What does it really mean for a number to be irrational?</p>
<p>Well, even though we don&#39;t want to say &quot;irrational&quot; is &quot;not rational&quot;, we can draw inspiration from what the latter to find a better definition. We say a number $x$ is rational if it can be written in the form $x=\frac{m}{n}$ where $m$ and $n$ are integers. Or, equivalently, $x$ is rational if there exists integers $m$ and $n$ such that $x - \frac{m}{n} = 0$. Since we&#39;re using subtraction here, there&#39;s a natural way to think of rationality in terms of distance; a number is rational if it is distance 0 away from some integer fraction. This gives us a nice way to think of irrationality.</p>
<p><strong>Definition:</strong> A number $x$ <strong>irrational</strong> if for all integers $m$ and $n$, $|x-\frac{m}{n}| \neq 0$. In other words, a number $x$ is irrational if it is some distance away from every rational number.</p>
<p>We add the asbolute value signs since we&#39;re quanitifying distance, and we don&#39;t care if a number is less than or greater than any rational number, just that it is not exactly equal to one of them.</p>
<hr>
<p>Some of you may be skeptical of what I&#39;ve just laid out, since if you&#39;re familiar with mathematical quantifiers, it does look like there is some negation work that is not explicit has been used under the cover of my words. Even so, the point is we have arrived at a distinct, specific definition of the property we set out to prove, allowing us to try and prove a <em>positive</em> claim as opposed to a negative one (like in proof by contradiction).</p>
<h2 id="the-new-proof">The New Proof</h2>
<p>We can rewrite our claim now as such:</p>
<p><strong>Claim: $\forall m,n \in \mathbb{Z}, \ |\sqrt{2} - \frac{m}{n}| \neq 0$</strong></p>
<p>That first part just means $m$ and $n$ are integers. We can now do our proof fairly quickly.</p>
<p><strong>Proof:</strong> Note that $1&lt;2&lt;\frac{9}{4}$, therefore $1&lt;\sqrt{2}&lt;3/2$. So the only rationals we care about comparing $\sqrt{2}$ are the ones in between $1$ and $\frac{3}{2}$, since it&#39;s apparent that any number outside this range will have a non-zero distance away from $\sqrt{2}$. Therefore, let&#39;s take our integers $m$ and $n$ such that they are positive, and $1&lt;\frac{m}{n}&lt;\frac{3}{2}$. Let&#39;s also take a second to note we can add these inequalities, giving us that $\sqrt{2} + \frac{m}{n} &lt; 3 \rightarrow n\sqrt{2} + m &lt; 3n$.</p>
<p>Now we can do some simple algebra on our claim to show it true.</p>
<center>
$\large{\bigg |\sqrt{2} - \frac{m}{n} \bigg | = \frac{|n\sqrt{2} - m|}{n} \cdot \frac{n\sqrt{2} + m}{n\sqrt{2} + m} = \bigg |\frac{2n^2 - m^2}{n(n\sqrt{2} + m)} \bigg |}$
</center>

<p>Let&#39;s examine the numerator. Every integer, $x$, has some number of factors of 2 in its prime factorization i.e. $x = 2^\alpha \cdot C$ where C is the rest of its factors. When you square that integer, the number of 2s in the denominator doubles $x^2 = 2^{2\alpha}\cdot C^2$. So, we can write $2n^2 = 2 \cdot 2^{2\alpha} \cdot C_1^2 = 2^{2\alpha + 1} \cdot C_1^2$. Similarly, $m^2 = 2^{2\beta} \cdot C_2^2$. The key detail here is that $2n^2$ has an <em>odd number</em> of factors of 2, while $m^2$ has an <em>even number</em> of factors of 2, and therefore cannot be the same number! And since they are integers, then $|2n^2 - m^2| \geq 1$.* Continuing on,</p>
<center>
$\large{\bigg |\sqrt{2} - \frac{m}{n} \bigg | = \bigg |\frac{2n^2 - m^2}{n(n\sqrt{2} + m)} \bigg | \geq \frac{1}{n(3n)} = \frac{1}{3n^2} }$
</center>

<p>We simplified the denominator with the inequality we found at the start. But look at what we have here!</p>
<center>
$\large{\bigg |\sqrt{2} - \frac{m}{n} \bigg | \geq \frac{1}{3n^2} }$
</center>

<p>This means for any rational number with denominator $n$, $\sqrt{2}$ is at least a distance $\frac{1}{3n^2}$ away from that rational! Therefore, $|\sqrt{2} - \frac{m}{n}|$ can never equal 0, and we have thus proved our claim and that $\sqrt{2}$ is irrational.</p>
<h2 id="conclusion">Conclusion</h2>
<p>A lot of this can seem like nitpicking definitions and being overly pedantic, and to a certain extent I agree. I mean, even in the proof above we sort of implicitly assume $\sqrt{2}$ is irrational at (*)! When we said $2n^2 \neq m^2$, you could rearrange that to get $\sqrt{2} \neq \frac{m}{n}$. In our definition above, this would only constitute as being &quot;not rational&quot; as opposed to &quot;irrational&quot;, but we are so subtely tweaking our interpretation of this fact to make it useful. When differences between proofs are this minute in terms of what we are saying, it seems hard to take any of what we talked about today as practical. We even turned to the definition of rationality to come up with a &quot;better&quot; definition of irrationality, so what&#39;s even the point in trying to discern minutiae of our constructs. </p>
<p>Even so, it&#39;s a good exercise in thinking about how we arrive at &quot;facts&quot; or &quot;knowledge&quot;. When can we prove something by contradiction, and even if we can, is there a more convincing argument? Are there possible cases we might be leaving out and forgetting? Are there some things that we cam <em>only</em> prove directly or indirectly (answer is <a href="https://math.stackexchange.com/questions/243770/can-every-proof-by-contradiction-also-be-shown-without-contradiction">yes</a>)?</p>
<p>These questions are what underpin so much that we naturally gravitate towards, and there&#39;s a reason why they&#39;ve been examined so harshly. These questions literally <a href="https://en.wikipedia.org/wiki/Russell%27s_paradox">uprooted math</a> and led to some of the most famous, mind-blowing results the <a href="https://en.wikipedia.org/wiki/G%C3%B6del%27s_incompleteness_theorems">field has ever seen</a>. So always ask yourself, &quot;What can I )<em>assume</em>, and what do I <em>know</em>?&quot;</p>
]]></description>
         <link>http://xperimex.github.io/blog/constructive-proofs</link>
         <guid isPermaLink="true">http://xperimex.github.io/blog/constructive-proofs</guid>
         <dc:creator><![CDATA[Adi Mittal]]></dc:creator>
      </item>
      <item>
         <title><![CDATA[Perimeters and Parameterizations]]></title>
         <description><![CDATA[How bees outsmart us all 

 <blockquote>
<blockquote>
<p>What shape has the largest area to perimeter ratio?</p>
</blockquote>
</blockquote>
<p>Some might have a guess, or an intuitition for what the answer should be, but it&#39;s a surprisingly difficult question to pin down as a proof. In fact, a rigorous proof wasn&#39;t given until around 1840 (J. Steiner)!</p>
<h2 id="some-observations">Some Observations</h2>
<p>There are some facts about our ideal shape we can observe quickly. First, it has to be <strong>convex</strong>_**. For if our shape was concave, we could always add more area with simple reflections.</p>
<center style="color: #666;">
<img src="/img/area-perimeter/concave-to-convex.png">
<p>We can get free area by reflecting over the blue line.</p>
</center>

<p>This can also be seen to work for not just polygons but curves as well, where instead of reflecting over vertices we can reflect over tangents.</p>
<p><img src="/img/area-perimeter/cave-vex-curve-fix.png"></p>
<center style="color: #666;">
<p>Concavity is wasted. Credit: Wikipedia</p>
</center>

<p>Further, in a similar argument, there has to be a type of <strong>perimeter-symmetry</strong> to our shape. For any way of dividing our shape into two equal perimeters, the areas enclosed by this dividing line must be equal. If they were not, one half would be bigger than the other, and we could just reflect that bigger half over the line to get a shape with the same perimeter but greater area (as we would have two copies of the bigger half glued together, as opposed to the bigger half attached to the smaller half).</p>
<p><img src="/img/area-perimeter/perimeter-symmetry.png"></p>
<center style="color: #666;">
<p>If area 1 was bigger than area 2, we can just replace area 2 with a reflection of area 1. We can then smooth out any cocavities the same way we did before.</p>
</center>

<p>This then also gives us a way to half our problem. Literally: instead of looking for the curve that encloses the most area for the same perimeter, we can instead look for the <em>arc</em> that encloses the most area with its endpoints connected by a fixed straight line. Then we can just reflect over it and we&#39;re good. So let&#39;s look at an arc.</p>
<p><img src="/img/area-perimeter/triangle-max.png"></p>
<center style="color: #666;">
<p>We can divide the area of our arc into 3 sections with an inscribed triangle.</p>
</center>

<p>Is there any way we can increase the area of this arc? With the above diagram, we have divided the area into 3 sections. Since we want to keep the arc&#39;s perimeter fixed, we can&#39;t really affect areas 1 and 2. But 3 we can maximize easily. For a triangle with 2 fixed side-lengths and the angle in between them, the area of the triangle is $ab\sin\theta$, which is maximized when $\theta$ is a right angle. So, we can increase the arc&#39;s overall area by picking a point along the curve, and having it such that it always forms a right triangle with the base of the arc. </p>
<p>So, to maximize the area of the arc, we want this to be true for <em>any</em> point picked along the curve. What curve is defined by forming a right triangle with its base at every point? It&#39;s a <strong>semi-circle</strong>! By fixing the base-length as well as the right angle restriction, it happens to also fix all radial lines from the mid point of the base. So finally reflecting back over the line as our second observation suggests, the shape that encloses the most area for a given perimeter is a <strong>circle</strong>.</p>
<p>…that is if such a shape exists. What we have really shown is that <strong>IF</strong> there is a shape that encloses the most area for a given arc length, <strong>THEN</strong> it is a circle. We have not necessarily shown that there is a shape. Intuitively, it seems a bit frivolous to worry about it since it just makes sense that there is only so much you can do to spread a curve out, but it is worth taking a second to do so. For, if the problem was, &quot;What shape encloses the <em>least</em> area for a given perimeter?&quot;, there is no such shape we can give. But this is a nit-picking detail that can be shown with not much difficulty using some calculus and limiting processes, but is worth keeping in mind. </p>
<p>Some might know the answer off the top of their head, and some might be able to guess, but the answer is unsurprisingly a circle. And we see that this is realized all throughout nature. Bubbles are circular since for a fixed amount of gas (i.e. volume), the sphere requires the least surface area to accomodate it (and therefore put the least amount of stress on the bubble). Rain drops, too, would be perfectly spherical if not for gravity.</p>
<h2 id="the-analytic-approach">The Analytic Approach</h2>
<p>With more robust tools, we can prove this more directly—albeit in a more overkill way. Our problem of finding the greatest area per perimeter is a byproduct of the <strong>isoperimetric inequality</strong>: for a given perimeter/arc length of a curve $L$ that encloses an area $A$, then $4 \pi A \leq L^2$. The proof isn&#39;t long, but requires some less accessible calculus machinery. The below is adapted from Erhard Schmidt&#39;s 1938 proof.</p>
<p><strong>PROOF:</strong> Let&#39;s parameterize a general simple closed curve $C$ (i.e. does not cross itself and ends where it starts), say $c(t) = (x(t),y(t))$. Since we care about arc length, we will parameterize $c(t)$ <em>with</em> arc length i.e. $\forall t \ |c&#39;(t)| = 1$ so that $c(L)$ is our end point of the curve. Now as it is a simple closed curve, $y(t)$ must be bounded as continuous functions on a bounded interval are bounded. So we can enclose our curve by two parallel lines, say, $l$ and $l&#39;$ that meet the curve $c(t)$ at say $t=0, t_{l}$.</p>
<p>Then, the area bounded by our curve $C$ is $A = \int_C x \ dy = \int_0^L x(t)y&#39;(t) \ dt$ by Green&#39;s theorem.</p>
<p>Now we can construct an &quot;approximate&quot; circle to our curve, that is parameterized by $r(t) = (x(t), z(t))$ and is also tangent to $l$ and $l&#39;$ (note that they are parameterized by the same x-vector). Call the radius of the circle $R$ and let its center be the origin of our coordinate system. Using our previous parameters, we will further fix this circle by</p>
<center>

$$ z(t) = \begin{cases} +\sqrt{R^2 - x(t)^2}, \ t \in [0,t_l] \\ -\sqrt{R^2 - x(t)^2}, \ t \in  (t_l, L] \end{cases} $$

</center>

<p>to ensure it lies in the $l$ and $l&#39;$ and is, well, a circle. Then, the area bounded by our circle is $\pi R^2 = - \int_\textrm{circle} y \ dx = - \int_0^L z(t)x&#39;(t) \ dt$.</p>
<p>Adding our areas together, we get,</p>
<center>

$2R\sqrt{A\pi} \leq A + \pi r^2 = \int_0^L xy&#39; - zx&#39; \ dt \leq \int_0^L \sqrt{(x^2 + z^2)(y&#39;^2 + x&#39;^2)} \ dt = LR$

</center>

<p>as $x^2 + z^2 = R^2$ and $y&#39;^2 + x&#39;^2 = 1$. The first inequality is by the arithmetic-geometric mean inequality (AM-GM), and the second one is by the Cauchy-Shwarz inequality applied to $(x, z)$ and $(y&#39;,x&#39;)$. So putting it all together, $2R\sqrt{A\pi} \leq LR$, or $4\pi A \leq L^2$. </p>
<center>
$\blacksquare$
</center>

<p>To get equality, we need to satisfy the first and last inequalities. To get equality in AM-GM, we need $A = \pi R^2$ and thus $L = 2\pi R$. To get equality in Cauchy-Scharwz, we want our vectors to be parallel i.e. $\frac{z}{x} = \frac{-x&#39;}{y&#39;} \rightarrow zy = -xx&#39;$. Substituting this into </p>
<center>
$(xy&#39; - zx&#39;)^2 = (x^2 + z^2)(y&#39;^2 + x&#39;^2)$ 
</center>

<p>from above nets that $x = \pm Ry&#39;$ and $y = \pm Rx&#39;$, or in other words by squaring and summing both equations, $x^2 + y^2 = R^2$, which is precisely the definition of a circle.</p>
<h2 id="so-">So?</h2>
<p>This problem generalizes to higher dimensions with higher dimension balls being the solution. But what I find most ineteresting is how quickly this problem changes with a slight tweak. We now know for sure circles are the best shape for a <em>single</em> container; an orange grows in the way for me to have the most amount of fruit in that single orange. But what if I had multiple oranges? Circles are awful to pack together as unlike, say, squares that nestle nicely together, circles leave so much extra room.</p>
<p><img src="/img/area-perimeter/circle_packing.jpeg"></p>
<center style="color: #666;">
<p>Even when optimally placed here, still about 10% of area is left uncovered.</p>
</center>

<p>So, if we wanted to create the optimal shape for stacking together using the least materials, what shape would that be? Clearly the answer is not a circle since it doesn&#39;t stack efficiently, and we have at the very least a square as our starting point. It turns out the answer, as nature has found its answer through bees, are hexagons. Perhaps another day we will go through the proof, but <a href="https://arxiv.org/pdf/math/9906042.pdf">Thomas Hale&#39;s original proof</a> of this Honeycomb conjecture is dense enough to leave alone for now.</p>
<p>What is even more interesting, is that unlike the isoperimetric problem from above, the 3D Honeycomb conjecture is still unsolved: what is the shape with the best area/surface area ratio to tesselate space? The <a href="https://en.wikipedia.org/wiki/Weaire%E2%80%93Phelan_structure">Weaire-Phelan structure</a> gives a non-obvious polyhedron that&#39;s the current record holder for known shapes, but it has not been proven to be the best.</p>
<p>The study of these minimal surfaces all tend to follow similar problems like the ones above, and just how deceptively difficult they are are what make them so interesting. Inspiration from physics and observed phenomena in nature are so helpful to guide us towards intuitions, the rigorous proof math demands is so often buried by our own self-defeating intuitions. If you&#39;re interested in more like this, I&#39;d suggest skimming over one of our previous discussions on <a href="http://xperimex.com/blog/variational-calculus/">the calculus of variations</a>.</p>
]]></description>
         <link>http://xperimex.github.io/blog/area-perimeter</link>
         <guid isPermaLink="true">http://xperimex.github.io/blog/area-perimeter</guid>
         <dc:creator><![CDATA[Adi Mittal]]></dc:creator>
      </item>
      <item>
         <title><![CDATA[The Language of Logic and Metatheoretic Magic]]></title>
         <description><![CDATA[Why even mathematicians should care about history 

 <!-- 
1. L1
  1a. ND1
2. L2
  2a. ND2
3. L=
  ND=

This is basically all of math: symbol manipulation. We don't check every right triangle to verify the Pythagorean theorem, we instead use rules that are sound.

1. metatheorems
2. soundness
3. completeness
4. compactness -->
<blockquote>
<blockquote>
<p><strong>Pythagorean Theorem</strong>: the sum of the squares of the length of the legs of a right triangle is equal to the square of the hypotenuse.</p>
</blockquote>
</blockquote>
<p>The Pythagorean theorem is perhaps the most famous statement in all of mathematics. $a^2 + b^2 = c^2$ is practically drilled into the minds of everyone that went through any form of secondary school education. </p>
<p>But let me ask you: how do you <em>know</em> it is true? It&#39;s not like you&#39;ve looked at every right triangle and checked it follows the theorem. There are many, many proofs of the Pythagorean theorem, but what makes you know that those fancy symbol manipulation is really legit? This might seem like an inane question, for math follows strict, rigorous, logical argument. But what makes this logical argument <em>valid</em>? Why do we trust logic so readily? There are many ideas that are intuitive that are false, and unintutive that are true, yet logic seems to get a pass from everyone? Why?</p>
<hr>
<p>Over the past year, I took my university&#39;s introductory sequence for logic, which were probably the most enlightening classes I&#39;ve ever taken. It forced me to reflect on not only what mathematics meant to me, but also what knowledge and deduction as a whole does too. This post is a summary collecting the highlights of the courses, so to act as a checkpoint to refer back to from future posts when I explore some of the most powerful ideas that have eluded me in what feels like a forgotten field of study.</p>
<p>As this will be a (quite a) bit of a longer post, the table of contents below will guide each section in the sequence they should be read, and all context needed for one section will be given in anything before it. I&#39;ll be following the conventions and terminology as per V. Halbach&#39;s <a href="https://users.ox.ac.uk/~logicman/"><em>The Logic Manual</em></a> and A. Eagle&#39;s <a href="https://ora.ox.ac.uk/objects/uuid:269144a3-6ca2-434b-90fe-75dd579cdbc1/download_file?file_format=application/pdf&amp;safe_filename=elements.pdf&amp;type_of_work=Book"><em>Elements of Deductive Logic</em></a>. Brief examples will be given, but for more examples and exercises, see the texts above. For the best viewing experience, read this on a computer or wider-screen device for the equations to format as they were intended to be.</p>
<h2 id="table-of-contents">Table of Contents</h2>
<ol>
<li><a href="#part-1-the-language-of-logic">The Language of Logic</a><ul>
<li><a href="#what-even-is-logic-">What even is logic?</a></li>
<li><a href="#-mathcal-l-_1-a-first-attempt">$\mathcal{L}_1$: A First Attempt</a><ul>
<li><a href="#connectives">Connectives</a></li>
<li><a href="#the-syntax-and-semantics-of-mathcal-l-_1-">Syntax and Semantics of $\mathcal{L}_1$</a></li>
<li><a href="#validity-of-an-argument">Validity of an Argument</a></li>
<li><a href="#proof-systems-and-natural-deduction">Proof Systems and Natural Deduction</a></li>
</ul>
</li>
<li><a href="#-mathcal-l-_2-the-logical-quantifiers">$\mathcal{L}_2$: The Logical Quantifiers</a><ul>
<li><a href="#predicates-and-constants">Predicates and Constants</a></li>
<li><a href="#quantifiers">Quantifiers</a></li>
<li><a href="#domains">Domains</a></li>
<li><a href="#satisfaction-and-truth-in-mathcal-l-_2-">Satisfaction and Truth</a></li>
<li><a href="#natural-deduction-2-0">Natural Deduction 2.0</a></li>
</ul>
</li>
<li><a href="#-mathcal-l-_-identity-and-definite-descriptions">$\mathcal{L}_=$: Identity and Definite Descriptions</a><ul>
<li><a href="#natural-deduction-2-5">Natural Deduction 2.5</a></li>
<li><a href="#numerical-claims">Numerical Claims</a></li>
<li><a href="#definite-descriptions">Definite Descriptions</a></li>
<li><a href="#a-quick-aside-on-identity">An Aside on Identity</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#part-2-introduction-to-metatheory">Introduction to Metatheory</a><ul>
<li><a href="#principle-of-mathematical-induction">Principle of Mathematical Induction</a></li>
<li><a href="#truth-functions">Truth Functions</a></li>
<li><a href="#substitution">Substitution</a></li>
<li><a href="#disjunctive-normal-form-and-expressive-adequacy">Disjunctive Normal Form and Expressive Adequacy</a></li>
<li><a href="#duality">Duality</a></li>
</ul>
</li>
<li><a href="#part-3-soundness-and-completeness">Soundness and Completeness</a><ul>
<li><a href="#soundness">The Soundness Theorem</a></li>
<li><a href="#completeness">The Completeness Theorem</a><ul>
<li><a href="#deductive-completeness">Deductive Completeness</a></li>
<li><a href="#maximally-consistent-sets">Maximally Consistent Sets</a><ul>
<li><a href="#constructing-a-maximally-consistent-set">Constructing Maximally Complete Sets</a></li>
<li><a href="#satisfying-a-maximally-consistent-set">Satisfying Maximally Complete Sets</a></li>
</ul>
</li>
<li><a href="#the-proof-of-completeness">Proof of the Completeness Theorem (of $\mathcal{L}_1$)</a></li>
<li><a href="#completeness-of-other-logics">Completeness of Other Logics</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#part-4-what-s-next-">What&#39;s Next?</a><ul>
<li><a href="#more-to-be-studied-">More To Be Studied!</a></li>
<li><a href="#natural-language-and-grice-s-maxims">Natural Language and Grice&#39;s Maxims</a></li>
<li><a href="#extensions-of-logic">Extensions of Logic</a><ul>
<li><a href="#higher-order-logics">Higher-Order Logic</a></li>
<li><a href="#universal-logics">&quot;Universal&quot; Logics</a></li>
<li><a href="#multivalue-and-fuzzy-logics">Multivalue and Fuzzy Logics</a></li>
<li><a href="#altering-the-axioms">Altering the Axioms</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#conclusion">Conclusion</a></li>
</ol>
<h1 id="part-1-the-language-of-logic">Part 1: The Language of Logic</h1>
<h2 id="what-even-is-logic-">What Even is Logic?</h2>
<!-- This seems like a broad question to open with, but it's an important one to make clear. -->
<p>English is bad. Notoriously so. Try interpreting the following sentence: &quot;The old man the boat.&quot; This might not even read as a correct sentence to some of you. The <strong>lexical ambiguity</strong> in that &quot;man&quot; is being used as a verb, even if it is more commonly a noun, is what makes this sentence lead one astray. Or, what about, &quot;The professor said there would be an exam on Monday.&quot; Does the professor mean there will be an exam to be taken on the upcoming Monday, or was it that this past Monday he claimed there would be an exam in the indeterminate future? The <strong>structural ambiguity</strong> inherent to what &quot;on Monday&quot; qualifies makes the sentence on its own unclear.</p>
<p>English—and <strong>natural language</strong> as a whole—relies on expectations being met by both the speaker and listener for effective communication. We&#39;ll touch on this more later, but the inherent vagueness of our language, while gives it the nuance that we praise in art and literature, makes it really hard to analyze the truth of what people claim when they talk, especially in writing. Inflection and tone may give cues to what is precisely being said, but sometimes we want the content of our statement to be independent of any necessary human interpretation or judgement.</p>
<p>Take the following claim: &quot;If Socrates is a man, then he is mortal. Socrates is a man. Therefore, Socrates is mortal.&quot; Few would dispute this argument, but there is very little content we needed to be okay with this argument. We don&#39;t care who Socrates is, or what it means to be a mortal or a man; there is something embedded into the nature of the argument that makes it good. &quot;The Earth is flat if 2+2=5. 2+2=5. Thus the Earth is flat,&quot; is a perfectly good argument <em>assuming</em> that 2+2=5, so while it might not be true, it certainly is still a good inference given those facts. &quot;If $P$, then $Q$. $P$. Therefore, $Q$,&quot; seems to always be a sound claim.  </p>
<p><strong>Logic, in this way, is the study of valid arguments.</strong> Given a set of <strong>premises</strong>, what <strong>conclusions</strong> can we deduce?</p>
<h2 id="-mathcal-l-_1-a-first-attempt">$\mathcal{L}_1$: A First Attempt</h2>
<p>Above we already were able to begin generalizing a little bit. We came up with the general form, &quot;If $P$, then $Q$. $P$. Therefore, $Q$.&quot; $P$ and $Q$ could be <em>almost</em> any sentence, and that argument would always hold. Almost any sentence, in that our sentences have to be <strong>truth evaluable</strong>; parsing questions or exclamations does not elicit any new information for our claims, so it does not really make sense to consider them. Even if we do not know if $P$ and $Q$ are actually true or false, we can still consider the different cases to check our argument structure. </p>
<p>Here we have the beginning of our first formal language: the logic of $\mathcal{L}_1$. We have already been able to characterize sentences in the form of <strong>sentence letters</strong> i.e. $P$ and $Q$, but if we need more we can add $R$, $P_2$, $Q_{3984}$, and others if we need more basic sentences (by convention, only $P,Q,R$ are the allowable sentence letters, with additional ones being subscripted). But this is a bit primitive. </p>
<h3 id="connectives">Connectives</h3>
<p>What makes arguments in English interesting is not the basic sentences, but how we are able to link them together via &quot;If… then…&quot;, &quot;…and…&quot;, &quot;…or…&quot;, and other conjunctions. Can we formalize these in any way?</p>
<p>Let&#39;s think about a simple one: &quot;…and…&quot;. Just like before, we can only care about sentences that are true or false, so a natural question will be when is &quot; $P$ and $Q$ &quot; true or false? &quot;…and…&quot; unifies two disparate sentences, so if the whole sentence was true, we would expect what ever is on either side of the &quot;and&quot; to also be true. To say that, &quot;Grass is green and the Earth is flat,&quot; is a true sentence seems to ignore what the sentence is claiming. &quot;…and…&quot; states both subsentences &quot;Grass is green&quot; and &quot;The Earth is flat&quot; together at once, so if we think it is true, then both necessarily seem to have to be true, too. We can represent this as a <strong>truth table</strong>. </p>
<center>
$
\begin{array}{c|c|c}
P &amp; Q &amp; (P \wedge Q) \\ \hline
T &amp; T &amp; T  \\
T &amp; F &amp; F  \\
F &amp; T &amp; F  \\
F &amp; F &amp; F  \\
\end{array}
$
</center>

<p>where $T$ means the sentence is true and $F$ false. Whenever $P$ and $Q$ are not both true, there conjunction is not either. As seen in the table above, we don&#39;t write &quot;…and…&quot; in $\mathcal{L}_1$, but rather use the symbol $\wedge$. </p>
<p>We call $\wedge$ a <em>connective</em>, for it connects two sentence letters together. Below are some other commonly used English connectives formalized in $\mathcal{L}_1$ with their corresponding truth tables.</p>
<center>
$
\begin{array}{c|c|c}
\textbf{English} &amp; \mathcal{L}_1 &amp; \textbf{Truth Table} \\ \hline
\textrm{…and…}             &amp; \wedge &amp;<br>          \begin{array}{c|c|c}
          P &amp; Q &amp; (P \wedge Q) \\ \hline
          T &amp; T &amp; T  \\
          T &amp; F &amp; F  \\
          F &amp; T &amp; F  \\
          F &amp; F &amp; F  \\
          \end{array} 
  \\ 
\hline
\textrm{…or…}              &amp; \ \vee \ \ &amp;<br>          \begin{array}{c|c|c}
          P &amp; Q &amp; (P \vee Q) \\ \hline
          T &amp; T &amp; T  \\
          T &amp; F &amp; T  \\
          F &amp; T &amp; T  \\
          F &amp; F &amp; F  \\
          \end{array}
  \\
\hline
\textrm{It is not the case that…}          &amp; \neg &amp;<br>          \begin{array}{c|c}
          P &amp; \neg P \\ \hline
          T &amp; F \\
          F &amp; T  \\
          \end{array}
\\
\hline
\textrm{If…then…}          &amp; \rightarrow &amp;<br>          \begin{array}{c|c|c}
          P &amp; Q &amp; (P \rightarrow Q) \\ \hline
          T &amp; T &amp; T  \\
          T &amp; F &amp; F  \\
          F &amp; T &amp; T  \\
          F &amp; F &amp; T  \\
          \end{array}
\\
\hline
\textrm{…if and only if…}  &amp; \leftrightarrow &amp;<br>          \begin{array}{c|c|c}
          P &amp; Q &amp; (P \leftrightarrow Q) \\ \hline
          T &amp; T &amp; F  \\
          T &amp; F &amp; T  \\
          F &amp; T &amp; T  \\
          F &amp; F &amp; F  \\
          \end{array}
\\
\end{array}
$
</center>

<p>It&#39;s worth taking a second to make sure you can get behind that these formalizations are reasonable. I won&#39;t go through all of them as we did with &quot;…and…&quot;, but there are some things to take note of that do differ a bit in English.</p>
<ul>
<li>$\vee$ is specifically the truth table of <strong>inclusive or</strong>. In English, if one says &quot;I&#39;ll either buy a pair of sneakers or sandals,&quot; we expect that person to usually just buy one option or the other, not both. $\vee$ allows the option for both, but does not require it to be true.</li>
<li>$\rightarrow$ is technically different from &quot;If…then…&quot;, even though I put them in the same row in the table. When we say, &quot;If a butterfly lands in North America, then there will be a earthquake in Australia tomorrow&quot;, we can definitely say that is false if the butterfly does land in North America and no earthquake occurs, since they are definitely not causally related then. But if the butterfly does NOT land in North America, then we are in no position to say whether or not there is a relationship then since we have nothing to observe. Similarly, if an earthquake happens, we can&#39;t say if that was because of the butterfly or not regardless of what happens since correlation and causation are different. So really, the truth table for &quot;If…then…&quot; is
<center>
$
\begin{array}{c|c|c}
P &amp; Q &amp; \textrm{If} \ P \ \textrm{then} \ Q \\ \hline
T &amp; T &amp; ?  \\
T &amp; F &amp; F  \\
F &amp; T &amp; ?  \\
F &amp; F &amp; ?  \\
\end{array}
$
</center>
We say it is not <strong>truth functional</strong> for those question marks there since we cannot evaluate whether that sentence is true or not, but for the sake of convenience, we use $\rightarrow$ with the completed table.</li>
</ul>
<!-- Talk about material implication vs. counterfactual later -->
<h3 id="the-syntax-and-semantics-of-mathcal-l-_1-">The Syntax and Semantics of $\mathcal{L}_1$</h3>
<p>Now, we can upgrade from sentence letters to complex sentences in our logic. We will define a sentence in $\mathcal{L}_1$ as follows:</p>
<ol type="i">
<li> All sentence letters $P, Q, R, P_1,…$ are sentences. </li>
<li> If $\Phi$ and $\Psi$ are sentences, then $\neg\Phi$, $(\Phi \wedge \Psi)$, $(\Phi \vee \Psi)$, $(\Phi \rightarrow \Psi)$, and $(\Phi \leftrightarrow \Psi)$ are sentences. </li>
<li> Nothing else is a sentence. </li>
</ol>

<p>Note the use of parantheses to bracket the sentences. This is our way to remove all structural ambiguity by clearly stating the <strong>scope of the connectives</strong>; there is no question that $(P \wedge (Q \vee R))$ is different from $((P \wedge Q) \vee R)$ as the parantheses explicitly denote the <strong>scope</strong> of the connectives to what subsentences they are linking together. There are conventions to remove these brackets for convenience, which I may default to later, but as a whole, are not important. </p>
<p>The last detail we are missing are <strong>interpretations</strong>. Before, we were talking about how logic does not care about human judgement, but we can consider the judgement of the <em>universe</em>. What is the truth value of the sentence $\neg(P \wedge Q \rightarrow P \vee R)$? We could make a truth table, but clearly the truth of the sentence depends on the truth values of $P$, $Q$, and $R$. So under an <strong>$\mathcal{L}_1$-interpretation</strong> or <strong>$\mathcal{L}_1$-structure</strong> that assigns a truth value to every sentence letter, we can assign truth values to sentences. For example, if we let a structure $A$ be such that $|P|_A = T$, $|Q|_A = T$, and $|R|_A = F$, then $|\neg(P \wedge Q \rightarrow P \vee R)|_A = F$ by its truth table. The idea of a structure is that it is a <strong>model of a universe</strong>, where we designate certain sentences/facts to be true or false, and see how the rest of the other complex facts (that are linked by connectives) change in accordance to that possible universe.</p>
<p><strong>Notation:</strong> $|\cdot|_A$ will stand for the <strong>meaning</strong> or <strong>semantics</strong> under a structure $A$.</p>
<p>Now most logical sentences one encounters will be true sometimes, and false sometimes depending on the structure its evaluated in. But consider the sentence $(P \vee \neg P)$. Looking at its truth table,</p>
<center>
$
\begin{array}{c|c}
P &amp; P \vee \neg P \\ \hline
T &amp; T \\
F &amp; T  \\
\end{array}
$
</center>

<p>Every structure assigns a truth value to every sentence letter, so $P$ must be true or false in every structure, but regardless, $(P \vee \neg P)$ is always true. <strong>Tautologies</strong> or <strong>logical truths</strong> are in a sense, facts of nature, for no matter what universe we are looking at, &quot;Either the sky is blue or it is not&quot; will be true. <a href="http://xperimex.com/blog/constructive-proofs/">At least, usually</a>.</p>
<p>On the other hand, <strong>contradictions</strong> like  $(P \wedge \neg P)$ are false in every structure.</p>
<p>For future reference, the following notation will be helpful. For a given structure $A$ and sentences $\Phi$ and $\Psi$ :</p>
<ul>
<li>If $|\Phi|_A = T$, we say $A$ <strong>satisfies</strong> $\Phi$, written $A \vDash \Phi$</li>
<li>If $|\Phi|_A = F$, we say $A$ <em>does not satisfy</em> $\Phi$, written $A \nvDash \Phi$</li>
<li>If $\Phi$ is a tautology, i.e. $A \vDash \Phi$ for all structures $A$, we just write $\vDash \Phi$</li>
<li>If $\Phi$ is a contradiction, i.e. $A \nvDash \Phi$ for all structures $A$, we just write $\Phi \vDash$</li>
<li>If $|\Phi|_A = |\Psi|_A$ for all strucutres $A$, we say $\Phi$ and $\Psi$ are <strong>logically equivalent</strong>, written $\Phi \equiv \Psi$</li>
</ul>
<p>The last bullet point is just to say that there are lots of sentences that express the exact same truth table despite being written differently. For example, $P \rightarrow Q \equiv \neg P \vee Q$, so it&#39;s useful to say when to sentences are actually essentially the same.</p>
<h3 id="sets-of-sentences">Sets of Sentences</h3>
<p>In addition to the semantics of individual sentences, we can discuss <em>sets of sentences</em> too. Consider $\Gamma = \{\Phi, \Psi,…\}$. </p>
<ul>
<li>A structure $A$ satisfies $\Gamma$ if and only if $|\gamma|_A = T \ \ \ \forall \gamma \in \Gamma$, written $A \vDash \Gamma$</li>
<li>We say $\Gamma$ is <strong>consistent</strong> or <strong>satisfiable</strong> if and only if there is a structure $A$ such that $A \vDash \Gamma$</li>
</ul>
<h3 id="validity-of-an-argument">Validity of an Argument</h3>
<p>We are finally in a position to start talking concretely and specifically what makes a good argument. </p>
<p>When someone has argued a claim (conclusion) from a series of facts and assumptions (premises), we want there to be a substantive connection between their premises and the conclusion. Just like with our truth table for &quot;If…then…&quot;, we know there is no connection if there is a scenario in which our premises are true and our conclusion isn&#39;t. <strong>So if an argument is valid, then whenever the premises are true, the conclusion must also be true</strong>.</p>
<p>We can formalize this a little bit with the notion of semantic entailment:</p>
<p><strong>Definition:</strong> Given a set of sentences (premises) $\Gamma = \{\Phi, \Psi,…\}$ and a single sentence $\varphi$ (conclusion), we say that $\Gamma$ <strong>semantically entails</strong> $\varphi$ if and only if for all structures $A$, if $A \vDash \Gamma$, then $A \vDash \varphi$.</p>
<p>In other words, whenever all of our premises are true, our conclusion is true.</p>
<p>When $\Gamma$ semantically entails a sentence $\varphi$, denoted $\Gamma \vDash \varphi$, then $\varphi$ is a valid conclusion from premises $\Gamma$. It&#39;s called semantic entailment since we are working with the semantics of the individual sentences, namely their truth values. In the language of consistency, we can also say that <span id = "valid-inconsistency">$\Gamma \vDash \varphi$ if and only if $\Gamma \cup \{\neg \varphi\}$ is inconsistent</span>.</p>
<hr>
<p><strong><span id = "valid-inconsistency">Claim:</span></strong> $\Gamma \vDash \varphi$ if and only if $\Gamma \cup \{\neg \varphi\}$ is inconsistent.</p>
<p><strong>Proof:</strong> Suppose that $\Gamma \vDash \varphi$. Say that $A$ is a structure that satisfies $\Gamma$ i.e. $|\gamma|_A = T \ \ \ \forall \gamma \in \Gamma$. Then by our assumption, $|\varphi|_A = T$. By the rules for $\neg$, then $|\neg \varphi|_A = F$. For any structure $B$ that does not satisfy $\Gamma$, $\exists \gamma \in \Gamma \ \ \ |\gamma|_B = F$. So, for all structures, at least one sentence in $\Gamma \cup \{\neg \varphi\}$ is false, so it is inconsistent. $ \ \blacksquare$</p>
<hr>
<p>It&#39;s worth pointing out that we have two uses for the symbol $\vDash$, one relating structures to sentences, and another relating sentences to other sentences. The context will specify which use we mean, but it is useful to keep in mind that we might double up on symbols when their related meanings are so similar.</p>
<p>Let&#39;s look at the example we&#39;ve been holding this whole time: &quot;If $P$, then $Q$. $P$. Therefore, $Q$.&quot; If this is a valid argument, then the formalization would say that $P \rightarrow Q, P \vDash Q$ is correct. We can verify this just by truth tables:</p>
<center>
$
\begin{array}{c|c||c}
(P \rightarrow Q) &amp; P &amp; \vDash &amp; Q \\ \hline
\color{blue}{T} &amp; \color{blue}{T} &amp; &amp; \color{blue}{T}  \\
F &amp; T &amp; &amp; F  \\
T &amp; F &amp; &amp; T  \\
T &amp; F &amp; &amp; F  \\
\end{array}
$
</center>

<p>Whenever the premises are true, so is the conclusion. While technically an okay way to check, it is inefficient. Imagine we had an argument with not 2, but even just 3, 4, or more sentence letters, since for every additional sentence letter in our premises, it doubles the number of rows in our truth table to check. Instead, we can show it just as easily with a proof by contradiction. <em>Suppose our argument is invalid</em> i.e. there is a structure where our premises are true and our conclusion is false.</p>
<center>
$
\begin{array}{c|c||c}
(P \rightarrow Q) &amp; P &amp; \vDash &amp; Q \\ \hline
T &amp; T &amp; &amp; F  \\
\end{array}
$
</center>

<p>But, if $P$ is true and $Q$ is false, then by the rules for $\rightarrow$, we have $P\rightarrow Q$ is false.</p>
<center>
$
\begin{array}{c|c||c}
(P \rightarrow Q) &amp; P &amp; \vDash &amp; Q \\ \hline
T &amp; T &amp; &amp; F  \\
F &amp;   &amp; &amp; 
\end{array}
$
</center>

<p>That contradicts our assumption that $P\rightarrow Q$ was true as a premise. So, it can&#39;t be the case that our argument is invalid.</p>
<h4 id="quicks-of-validity">Quicks of Validity</h4>
<p>Keep in mind our definition of a valid argument: $\Gamma \vDash \varphi$ if and only if whenever $\Gamma$ is satisfied, so is $\varphi$. Now consider the argument $P \wedge \neg P \vDash Q$. Is this valid? Even though the premises have nothing to do with the conclusion, surprisingly, <strong>this is valid</strong>. $P \wedge \neg P$ technically satisfies the condition that whenever it <i>is</i> true (never), so is $Q$; it never has the chance to fail our definition. For this we can write $P \wedge \neg P \vDash$ since it will entail everything by our definition, and anything can go on the right hand side of the turnstile, and this is why we shorten all contradicitions accordingly.</p>
<p>Similarly, we can do the same for tautologies, $\vDash P \vee \neg P$ since they will always be true, so certainly whenever whatever on the left is true, so is the tautology.</p>
<p>So we can have weird technically valid arguments like, &quot;The sky is blue and not blue, therefore the Earth is flat,&quot; or similarly that &quot;Squares have 5 corners, so either it will rain today or it won&#39;t.&quot; These both read as absurd, but they are technnically valid with our definition. These might seem like a flaw for our definition, but for the convenience of all the other arguments, I think it is worth accepting as an oddity of the system. You can also think of them as just sort of fact-of-the-matter statements; tautologies are entailed by everything since they don&#39;t care what makes you think they are true, they just are. Similarly with contradictions, your starting set of premises are just inconsistent, and it is just a bad argument; if you&#39;re willing to accept bad premises, you can deduce bad conclusions.</p>
<h2 id="proof-systems-and-natural-deduction">Proof Systems and Natural Deduction</h2>
<p>We have established quite a bit already in $\mathcal{L}_1$, but it is still not that elegant of a system. We now have a way to formalize English arguments, but our ways to validate them are still unwieldy. The only two ways we really have to verify statements is, in essence, brute force checking $\mathcal{L}_1$-structures to see if the argument fails anywhere. This is no better than checking every right-angled triangle to see if it satisfies the Pythagorean theorem. We want a systematic way to go about our arguments.</p>
<p>We want a <strong>proof system</strong>: given a set of premises $\Gamma$, we want to be able to manipulate them in some way to conclude $\varphi$. </p>
<p>For example, consider the argument $P \wedge Q, R \vDash P \wedge R$. Without checking any structures and evaluating truth tables, this argument should make sense. If we know $P \wedge Q$, i.e. $P$ <em>and</em> $Q$, we certainly know both $P$ and $Q$ are true individually, so we know $P$. Since we also know $R$ is true, then again it seems obvious we know $P$ <em>and</em> $R$ is also true together i.e. $P \wedge R$. We did not touch any semantics at all of our premises or conclusion (I used the word &quot;true&quot; as a means for accepting a premise), but rather just moved our sentence letters around in a sensible way to get the conclusion.</p>
<p>We just found two rules that make sense to have in our proof system: $\wedge$-Introduction and $\wedge$-Elimination.</p>
<center>
$
\begin{array}{ccc}
&amp; \wedge\textrm{-Intro} &amp; \\
\Phi &amp;   &amp; \Psi \\ \hline 
 &amp; \Phi \wedge \Psi &amp;   \\ 
\end{array}
\ \ \ \
\begin{array}{c}
\wedge\textrm{-Elim1} \\
\Phi \wedge \Psi   \\ \hline 
 \Phi  \\ 
\end{array}
\ \ \ \
\begin{array}{c}
\wedge\textrm{-Elim2} \\
\Phi \wedge \Psi   \\ \hline 
 \Psi  \\ 
\end{array}
$
</center>

<p>So our above proof of $P \wedge Q, R \vdash P \wedge R$ would look like</p>
<center>
$
\begin{array}{ccc}
\underline{P \wedge Q} &amp;   &amp;  \\
P &amp;  &amp; R  \\ \hline
  &amp; P \wedge R &amp;   \\ 
\end{array}
$
</center>

<p>Thinking through what the other connectives mean can give some intuitive rules for them too:</p>
<center>
$
\begin{array}{c|c|c}
\textbf{Connective} &amp; \textbf{Introduction} &amp; \textbf{Elimination} \\ \hline
\wedge &amp;  \begin{array}{c}
          \begin{array}{cc}
          \Phi &amp; \Psi \\
          \end{array} \\ \hline
          \Phi \wedge \Psi
          \end{array}<br>        &amp; \begin{array}{c}
          \Phi \wedge \Psi   \\ \hline 
          \Phi  \\ 
          \end{array}
          \ \ \ \
          \begin{array}{c}
          \Phi \wedge \Psi   \\ \hline 
          \Psi  \\ 
          \end{array}          \\  \hline
\vee &amp;  \begin{array}{c}
          \Phi   \\ \hline 
          \Phi \vee \Psi  \\ 
          \end{array}
          \ \ \ \
          \begin{array}{c}
          \Psi   \\ \hline 
          \Phi \vee \Psi  \\ 
          \end{array}
          &amp;   \begin{array}{c}
        \begin{array}{ccc}
                      &amp; [\Phi] &amp; [\Psi] \\
                      &amp; \vdots &amp; \vdots \\
        \Phi \vee \Psi &amp; \Delta &amp; \Delta \\
        \end{array} \\ \hline
        \Delta
        \end{array}  \\  \hline
\neg &amp;  \begin{array}{c}
        \begin{array}{cc}
        [\Phi] &amp; [\Phi] \\
        \vdots &amp; \vdots \\
        \Psi &amp; \neg\Psi \\
        \end{array} \\ \hline
        \neg \Phi
        \end{array}<br>     &amp;  \begin{array}{c}
        \begin{array}{cc}
        [\neg\Phi] &amp; [\neg\Phi] \\
        \vdots &amp; \vdots \\
        \Psi &amp; \neg\Psi \\
        \end{array} \\ \hline
        \Phi
        \end{array}  \\  \hline
\rightarrow &amp;   \begin{array}{c}
                [\Phi] \\
                \vdots \\
                \Psi   \\ \hline 
                \Phi \rightarrow \Psi  \\ 
          \end{array}<br>            &amp;  \begin{array}{c}
                \begin{array}{cc}
                \Phi &amp; \Phi\rightarrow\Psi \\
                \end{array} \\ \hline
                \Psi
                \end{array}   \\  \hline
\leftrightarrow &amp;  \begin{array}{c}
                    \begin{array}{cc}
                    [\Psi] &amp; [\Phi] \\
                    \vdots &amp; \vdots \\
                    \Phi &amp; \Psi \\
                    \end{array} \\ \hline
                    \Phi\leftrightarrow\Psi
                    \end{array}<br>                 &amp;  \begin{array}{c}
                    \begin{array}{cc}
                    \Phi &amp; \Phi\leftrightarrow\Psi \\
                    \end{array} \\ \hline
                    \Psi
                    \end{array}<br>                    \ \ \ \
                    \begin{array}{c}
                    \begin{array}{cc}
                    \Psi &amp; \Phi\leftrightarrow\Psi \\
                    \end{array} \\ \hline
                    \Phi
                    \end{array} 
                     \\ 
\end{array}
$
</center>

<p>The square brackets are <em>assumed premises</em>. They are not explicitly given, but, for the sake of argument, you can take a &quot;fake&quot; premise to demonstrate a rule, and discard that assumption after you&#39;ve used your rule. Some other comments on the rules:</p>
<ul>
<li>$\vee$-Intro basically says if you know one sentence, appending any other sentence via $\vee$ is certainly fine since you already have a known fact. $\vee$-Elim says if you know one or the other (or both) of $\Phi$ and $\Psi$ is true, but do not know which, you can deduce a new sentence $\Delta$ if it follows from either of the sentences.</li>
<li>$\neg$-Rules are basically proofs by contradiction. If $\Phi$ results in both $\Psi$ and $\neg\Psi$, $\Phi$ can&#39;t be held true since it would prove contradictory results. Similarly with assuming $\neg\Phi$.</li>
<li>$\rightarrow$-Intro follows in line with for-the-sake-of-argument. If we <em>assume</em> $\Phi$, and can deduce $\Psi$, then regardless if we know $\Phi$ or not, we can say that it would logically imply $\Psi$ as well. </li>
</ul>
<p>This specific proof system is known as <strong>natural deduction</strong>. These proof trees give us a direct way to interact with our premises in a way that we might normally do in English. However, some of these proofs do become huge quite quickly. Consider the proof of $P\rightarrow (Q\leftrightarrow R) \vdash P \wedge Q \leftrightarrow P \wedge R$:</p>
<p><img src="/img/intro-logic/sample_proof.png"></p>
<p>Some of you might have noticed a small change in notation; I&#39;ve been using $\vdash$ as opposed to $\vDash$. In proofs, since we are not considering structures and the truth values of our sentences, semantic entailment does not seem like the right way to describe the relationship between our premises and the conclusion. We now say $\Gamma \vdash \varphi$ if $\Gamma$ <strong>syntactically entails</strong>, or simply <strong>proves</strong> via our proof system, $\varphi$, since we are strictly only concerned with the symbols and the actual writing of the sentence as opposed to its truth.</p>
<p>But we should not forget our original goal of logic: to demonstrate arguments are valid, which involves $\Gamma \vDash \varphi$, which seems to have a very different meaning to $\Gamma \vdash \varphi$. It happens that our choice of rules above was not random. As we will see later, natural deduction is a <strong>sound system</strong>:</p>
<p><strong>Soundness Theorem:</strong> If $\Gamma \vdash \varphi$, then $\Gamma \vDash \varphi$.</p>
<p>Soundness can be thought of as the quality of <em>preserving truth</em>; we can rely on our proofs to deduce meaningful, accurate conclusions in our formal language. Given our rules, we would hope that these are sound, since they are based on how people typically argue in real life, too. You might come across other proof systems, but I can guarantee you, they are designed to be sound and useful. </p>
<hr>
<p>It&#39;s worth mentioning at this point we have similar notions for consistency in a proof based sense just as we have in a semantic sense. We say a set of sentences $\Gamma$ is <strong>ND-consistent</strong> (ND for natural deduction) if there exists a sentence $\Phi$ that $\Gamma$ does <em>not</em> prove; i.e. $\exists \Phi$ s.t. $\Gamma \nvdash_{ND} \Phi$. In general, we say $\Gamma$ is <strong>D-consistent</strong> if there is a sentence $\Gamma \nvdash_{D} \Phi$ in the deductive system $D$. A good way of thinking about this is if we have bad premises, we can deduce anything since our assumptions were contradictory in some way. For example, $\{P, \neg P\}$ is ND-inconsistent since by $\neg$-Elim, it can prove anything.</p>
<p>Fortunately enough for us, ND-consistency is equivalent to semantic consistency, but we&#39;ll see that later.</p>
<!-- ### Completeness

It's worth noting the direction that the Soundness Theorem argues: if something is provable, then it makes a valid argument. -->
<hr>
<p>This concludes our discussion of $\mathcal{L}_1$. The system and rules we&#39;ve outlined above is sometimes also referred to as <strong>propositional logic</strong>.</p>
<h2 id="-mathcal-l-_2-the-logical-quantifiers">$\mathcal{L}_2$: The Logical Quantifiers</h2>
<p>Let&#39;s go back to our very first argument we discussed: &quot;If Socrates is a man, then he is mortal. Socrates is a man. Therefore, Socrates is mortal.&quot; We were able to show it is valid in $\mathcal{L}_1$ by formalizing it, and either checking its truth table or with our proof system. Let&#39;s look at a very similar argument. &quot;All men are mortal. Socrates is a man. Therefore, Socrates is mortal.&quot; Perfectly reasonable. If we formalize this with our current logic, though, we end up with $P, Q \vDash R$, where $P$ is &quot;All men are mortal,&quot; $Q$ is &quot;Socrates is a man&quot;, and $R$ is &quot;Socrates is mortal&quot;. Clearly this is not a logical argument in $\mathcal{L}_1$, since we can just specify a structure where $|P|_A = |Q|_A = T$ and $|R|_A = F$ since they are separate sentence letters.</p>
<h3 id="predicates-and-constants">Predicates and Constants</h3>
<p>$\mathcal{L}_1$ is good for keeping sentences simple, but it lacks the nuance of the <strong>predicates</strong> English has; we will never be able to show the relation of men and mortality, as we can&#39;t express &quot;…are mortal&quot; nicely; relations between simpler sentences are covered by connectives, but relations between objects are not. We need something to convey <strong>properties</strong> somehow. Ideally, we want to be able to say Socrates is mortal, by first saying he is a man, and to further show that anything that <em>has the property of being a man</em> also <em>has the property of being mortal</em>.</p>
<p>To formalize &quot;Socrates is a man&quot;, we can introduce predicates kind of like connectives. Let&#39;s have $P^1$ stand for &quot;…is a man&quot;, and for convenience, we&#39;ll let the letter $|a|_A$ stand for the <strong>constant</strong> Socrates (remember, $|\cdot|_A$ denotes meaning). Then $P^1a$ is a nice compact way to write out &quot;Socrates is a man&quot;.</p>
<p>Now how do we formalize that this is a true sentence? We don&#39;t want to have to explicitly say $|P^1a|_A = T$, since then we would have to specify that for <em>everything</em> that is a man, there is a constant associated with that human and that when put together with $P^1$ forms a true statement.</p>
<p>Let&#39;s take a step back for a moment. If you had to explain to an alien precisely what a human is, how would you do it? You might describe some key traits for them, but the easiest way, in a universal sense, is just to show them by example. Give them a list of humans and have them extrapolate on their own. So perhaps a good semantics for predicates is to exactly that: we will let $|P^1|_A = \{\textrm{Socrates}, \textrm{Feynman}, \textrm{Noether},…\}$.</p>
<p>Then a natural way of defining truth would be that $|P^1a|_A = T$ if and only if $|a|_A \in |P^1|_A$. That sentence makes sense, since $|a|_A$ is an object/noun, and $|P^1|_A$ is a set of objects, so we can evaluate that, and since $|P^1|_A$ explicitly states all the objects that have that property, seeing if something has that property (like being a man) is a matter of being in the list of objects said to have it. &quot;Socrates is a man&quot; is true iff &quot;Socrates&quot; has the property &quot;is a man&quot; iff Socrates is in the set of all men.</p>
<p>I&#39;ve been putting a small superscript in our predicate $P^{\color{red}{1}}$. This is the <span style="color:red">arity index</span>, and basically says how many objects the predicate takes as an input. So, naturally we can have indices greater than 1 as well.</p>
<p>The predicate &quot;…like…&quot; is a perfectly good predicate, but it now qualifies <em>two</em> objects and relates them to each other. So if Alice likes Bob, we can write this as $P^2ab$ with the relevant meanings for $P^2$ as &quot;…likes…&quot; and the constants referring to Alice and Bob respectively. But note here, <strong>order matters</strong>. Just because Alice likes Bob, that does not necessarily mean Bob likes Alice and so for some structures it might be the case that $|P^2ab|_A \neq |P^2ba|_A$.</p>
<p>Just as arity 1 predicates had a set of objects as its semantics, arity 2 has a set of <strong>ordered pairs</strong> i.e. $|P^2|_A = \{\langle \textrm{Alice}, \textrm{Bob}\rangle, \langle \textrm{Davis}, \textrm{Edward} \rangle, \langle \textrm{Jack}, \textrm{Jack} \rangle \}$ would be a reasonable way to denote the predicate. And similarly, we say $|P^2ab|_A = T$ if and only if $\langle |a|_A, |b|_A \rangle \in |P^2|_A$. So 2-ary predicates define <strong>binary relations</strong>. </p>
<center>
$
\begin{array}{c|c|c}
\textbf{Expression} &amp; \textbf{Formalization} &amp; \textbf{Semantic Value} \\ \hline
\textrm{constants} &amp; a,b,c,… &amp; \textrm{objects}   \\ 
\textrm{sentence letter} &amp; P,Q,R,… &amp; \textrm{truth value} \ (T,F)  \\ 
\textrm{unary predicate} &amp; P^1,Q^1,R^1,… &amp; \textrm{set of objects}  \\ 
\textrm{binary predicate} &amp; P^2,Q^2,R^2,… &amp; \textrm{set of ordered pairs}  \\ 
\textrm{ternary predicate} &amp; P^3,Q^3,R^3,… &amp; \textrm{set of ordered triples} \\ 
\textrm{n-ary predicate} &amp; P^n,Q^n,R^n,… &amp; \textrm{set of n-tuples} \\ 
\end{array}
$
</center>

<p>In practice, the arity index usually doesn&#39;t need to be written, as it will be implied by the number of constants attached to the predicate i.e. $Pabc$ is clearly a ternary predicate, as if it wasn&#39;t, it would either be incomplete (&quot;a hates b and c, but likes ?&quot;), or it would accept too many arguments (&quot;If a then b&quot;; where does c go?). So in sentences like $Pa \wedge Pab$, each $P$ stands for a different predicate as implied by their arity.</p>
<p>This is the start of the more robust logic $\mathcal{L}_2$. Just for the formalities, here are some things we need to keep in mind over $\mathcal{L}_1$.</p>
<ul>
<li>Sentence letters are the same as 0-ary predicates; they accept no arguments.</li>
<li>In an $\mathcal{L_2}$-structure, we assign semantics to every predicate (either truth values or sets to predicates), as well as an object to every constant</li>
<li>Connectives work the same as they have done before</li>
<li>Truth for predicates are equivalent to membership of a set</li>
</ul>
<h3 id="quantifiers">Quantifiers</h3>
<p>So we now have a good way of storing properties of objects via the predicates they satisfy, so we have a good way of saying &quot;Socrates is a man&quot;. But now we need a way of saying, &quot;All men are mortal&quot;. It&#39;s that &quot;all&quot; that makes this difficult, since it does not refer to a specific man, but a <em>generic</em> one. </p>
<p>Let&#39;s generalize the sentence a bit more. What it really is saying, &quot;If one is a man, then they are mortal.&quot; Now we have this nice &quot;one&quot; acting a <strong>placeholder</strong> name for our generic man. Actually, for a generic <em>anything</em>. If we are talking about a turtle, we cannot say if they are mortal by this sentence since they have nothing to do with that claim. </p>
<p>In an even more mathematical way of looking at the sentence, it could read as, &quot;For all $x$: if $x$ is a man, then $x$ is mortal.&quot; That &quot;for all&quot; appears enough in arguments, we have formalize it as $\forall$, the <strong>universal quantifier</strong>. You might have seen this appear in math, and if not, I&#39;ve already been abusing its convenience in some previous proofs on this post.</p>
<p>So our sentence would look like $\forall x(Px \rightarrow Qx)$ where $P$ and $Q$ are predicates for being a person and mortal respectively.</p>
<p>$x$ is clearly not a constant, since, well, it is not constant; it does not have a fixed meaning. We then aptly call it a <strong>variable</strong>. But clearly, variables <em>can</em> take on certain meanings, so we also have <strong>variable assignments</strong> $\alpha, \beta,…$ that allow us to arbitrarily assign variables meanings in a formal way. For example, if we let $x$ mean Socrates in our structures, i.e. $|x|_A^\alpha = \textrm{Socrates} = |a|_A$, then our argument works by the truth rules for $\rightarrow$.</p>
<p>The &quot;opposite&quot; of the universal quantifier is the <strong>existential quantifier</strong> $\exists$, which instead of saying our sentence applies to all possible objects, $\exists x \Phi$ only claims that there is at least one object that satisfies the sentence $\Phi$. </p>
<hr>
<p>The <a href="#duality">duality</a> of the quantifiers can be found even in natural language. &quot;Everything is not a cow,&quot; as in $\forall x \neg Px$, is the same as saying, &quot;There does not exist a cow&quot;, or $\neg \exists x Px$. Similarly, &quot;There is something that is not a cow,&quot; or $\exists x \neg Px$, is equivalent to saying &quot;Not everything is a cow&quot; or $\forall x \neg Px$.</p>
<hr>
<p>However, not every <strong>formula</strong> with variables and quantifiers make a sentence. Consider $\forall x \exists y(Px \vee \neg Qxy \rightarrow Rz)$. This doesn&#39;t make that much sense since $z$ is just hanging out as a <strong>free variable</strong> as there is no quantifier claiming anything about $z$. And since $z$ is a variable, it&#39;s not like it has any semantic meaning, either. So we wouldn&#39;t call this a sentence, but a formula. Variables that are not free are <strong>bound</strong>.</p>
<p><strong>Definition:</strong> A formula is a sentence if and only if it has no free variables.</p>
<p>Similarly, $\forall y Qy \rightarrow Py$ wouldn&#39;t be called a sentence either, as depite how it looks, there is a free variable in $Py$ even though there is a $\forall y$ in the formula. You usually need parantheses to specify what the quantifiers bind. $\forall y(Qy \rightarrow Py)$ is a sentence, while the previous expression is not.</p>
<h3 id="domains">Domains</h3>
<p>The final extra detail we need is to specify <em>what</em> meanings our variables are allowed to be assigned. So in an $\mathcal{L}_2$-structure, we also specify a <strong>domain</strong> that specifies all the possible objects in the &quot;universe&quot; that we are discussing. All constants are assigned meanings from the domain, and our quantifiers use variable assignments that range over the domain.</p>
<h3 id="satisfaction-and-truth-in-mathcal-l-_2-">Satisfaction and Truth in $\mathcal{L}_2$</h3>
<p>Suppose $\Phi$ and $\Psi$ are $\mathcal{L}_2$ formulas, $v$ is a variable, $A$ is a structure, and $\alpha$ is a variable assignment. We say <strong>$\alpha$ satisfies $\varphi$ under $A$</strong>, or $|\varphi|_A^\alpha = T$, in the following way: </p>
<ul>
<li>$|\Phi v_1v_2…v_n|_A^\alpha = T$ iff $\langle |v_1|_A^\alpha, |v_2|_A^\alpha,…, |v_n|_A^\alpha  \rangle \in |\Phi|_A^\alpha$ where $\Phi$ is an n-ary predicate and each $v_i$ is a variable or constant</li>
<li>$|\neg\Phi|_A^\alpha = T$ iff $|\Phi|_A^\alpha = F$</li>
<li>$|\Phi \wedge \Psi|_A^\alpha = T$ iff $|\Phi|_A^\alpha = T$ and $|\Psi|_A^\alpha = T$</li>
<li>$|\Phi \vee \Psi|_A^\alpha = T$ iff $|\Phi|_A^\alpha = T$ or $|\Psi|_A^\alpha = T$</li>
<li>$|\Phi \rightarrow \Psi|_A^\alpha = T$ iff $|\Phi|_A^\alpha = F$ or $|\Psi|_A^\alpha = T$</li>
<li>$|\Phi \leftrightarrow \Psi|_A^\alpha = T$ iff $|\Phi|_A^\alpha = |\Psi|_A^\alpha$</li>
<li>$|\forall v \Phi|_A^\alpha = T$ iff for every variable assignment $\beta$ that differs from $\alpha$ in at most $v$, $|\Phi|_A^\beta = T$; in other words, $|\forall v \Phi|_A^\alpha = T$ iff $\Phi$ is satisfied when every thing except $v$ is fixed</li>
<li>$|\exists v \Phi|_A^\alpha = T$ iff there is at least one variable assignment $\beta$ that differs from $\alpha$ in at most $v$ where $|\Phi|_A^\beta = T$; in other words, $|\exists v \Phi|_A^\alpha = T$ iff $\Phi$ is satisfied for some value of $v$</li>
</ul>
<p>The normal connective satisfaction come from the standard truth tables we did before, and the quantifiers are exactly what you would imagine them to mean, just formalized in the new terminology we have to make it precise.</p>
<p>The truth of an $\mathcal{L}_2$ sentence is now easy given the above satisfaction rules:</p>
<p><strong>Definition:</strong> An $\mathcal{L}_2$ sentence $\varphi$ is true $|\varphi|_A = T$ iff $|\varphi|_A^\alpha = T$ for every variable assignment $\alpha$ over $A$.</p>
<p>Validity remains the same in $\mathcal{L}_2$, just with our updated definitions for structures and truth:</p>
<p><strong>Definition:</strong> Given a set of $\mathcal{L}_2$ sentences $\Gamma = \{\Phi, \Psi,…\}$ and a single sentence $\varphi$, we say that $\Gamma$ semantically entails $\varphi$ if and only if for all $\mathcal{L}_2$-structures $A$, if $A \vDash \Gamma$, then $A \vDash \varphi$.</p>
<h2 id="natural-deduction-2-0">Natural Deduction 2.0</h2>
<p>Rules for our original connectives $\wedge, \vee, \neg, \rightarrow, \leftrightarrow$ remain the same. We only need to add the rules for $\forall$ and $\exists$. It will be easier to write them out then explain them afterwards.</p>
<center>
$
\begin{array}{c|c|c}
\textbf{} &amp; \textbf{Introduction} &amp; \textbf{Elimination} \\ \hline
\forall &amp;   \begin{array}{c}
              \Phi[t/v]   \\ \hline 
              \forall v \Phi  \\ 
              \end{array} \ 
            { \textrm{for generic constant} \ t}
      &amp;  \begin{array}{c}
          \forall v \Phi   \\ \hline 
          \Phi[t/v]  \\ 
          \end{array}  \\  \hline
\exists &amp;  \begin{array}{c}
          \Phi[t/v]   \\ \hline 
          \exists v \Phi  \\ 
          \end{array}
          &amp;   \begin{array}{c}
        \begin{array}{cc}
                      &amp; [\Phi[t/v]] \\
                      &amp; \vdots \\
        \exists v \Phi &amp; \Psi \\
        \end{array} \\ \hline
        \Psi
        \end{array}  \ 
            { \textrm{for generic constant} \ t} \\
\end{array}
$
</center>

<p>The notation of $\Phi[t/v]$ is to highlight <strong>substitution</strong>: $\Phi[t/v]$ is the formula $\Phi$ with all occurrences of $v$ in it replaced with $t$. For example, if $\Phi = Px \wedge \forall y (Qxy \rightarrow Rx)$, then $\Phi[t/x] = Pt \wedge \forall y (Qty \rightarrow Rt)$.</p>
<p>Here is the intuition behind the new rules:</p>
<ul>
<li>$\forall$-Intro basically says if $t$ is a constant that does not appear anywhere else in our proof, it is in practice a &quot;dummy variable&quot;, and allows us to introduce a proper variable bound by $\forall$.</li>
<li>$\forall$-Elim says if we know $\Phi$ is satisfied by possible $v$, it is certainly true if $v$ is replaced by a specific $t$; if all men are mortal, certainly Socrates is mortal too</li>
<li>$\exists$-Intro is the formal way of saying if we see an occurence of $\Phi$, then there is some $v$ that satisfies $\Phi$; if you see a cow, you know there is at least one animal</li>
<li>$\exists$-Elim is a for-the-sake-of-argument style proof. While we may not know exactly <em>what</em> satisfies $\exists v \Phi$, if we can deduce some claim independent of the specific thing that satisfies it, we know that claim must also be true as it only relies on the existence of something. If we know there is at least one plant-eating animal—call it Bob—we can conclude that there are plants, since Bob eats plants, and that&#39;s true for all &quot;Bob&quot;s (a.k.a. plant-eating animals).</li>
</ul>
<p>With these added rules, we can now prove a lot of the things we already knew, such as:</p>
<ul>
<li>The mortality argument of $\forall x(Px \rightarrow Qx), Pa \vdash Qa$</li>
<li>The quantifier interplay $\neg \forall x Px \dashv\vdash \exists x \neg Px$</li>
<li>Standard tautologies and contradictions; $\vdash \forall x Px \vee \neg \forall x Px$, and $\forall x Px \wedge \neg \forall x Px \vdash$</li>
</ul>
<p>Here is an example worked proof from the additional exercises of <em>The Logic Manual</em> of $\forall y \exists x(Ryx \vee Qyx) \vdash \forall y (\exists x Ryx \vee \exists x Qyx)$:</p>
<p><img src="/img/intro-logic/sample_proof2.png"></p>
<p>Similarly, we will see that these rules are also sound.</p>
<h2 id="-mathcal-l-_-identity-and-definite-descriptions">$\mathcal{L}_=$: Identity and Definite Descriptions</h2>
<p>$\mathcal{L}_2$ gets us most of the way for what we want but there&#39;s one slight inconvenience: we don&#39;t have a notion of identity. Say we have a constant $a$  with semantic value $|a|_A = \textrm{Socrates}$. Then, if we have another constant $b$ such that $|b|_A = \textrm{Socrates}$, we have no good way of showing these constants are really &quot;the same&quot;; they might look different, but they function in the same way as both standing in for Socrates.</p>
<p>And in a philosophical, sense, identity is an important concept in ontologies and metaphysics, so it&#39;s worthwhile having a formal notion that we can refer to when picking apart arguments.</p>
<p>We could just specify the predicate, &quot;…is identical to…&quot; as a binary predicate letter in $\mathcal{L}_2$, but that means that the predicate might receive arbitrary meanings in different structures, and identity seems like a pretty unshakeable concept. It also might mean that we use different predicate letters in different formalizations, and we want this to be consistent for it to be useful.</p>
<p>This is what $\mathcal{L}_=$ is for. $\mathcal{L}_=$ is <em>exactly</em> like $\mathcal{L}_2$ in terms of structures and truth, but it has the one difference of having an extra predicate of $=$ to refer to identity. Some quick notes:</p>
<ul>
<li>As $=$ is a binary predicate, it relates two terms that are constants or variables (not formulas or sentences!)</li>
<li>By convention, we write $a=b$ as per the norm of math; we don&#39;t write $=ab$ as we would for a normal predicate/predicate letter</li>
<li>For variables/constants $s$ and $t$, $|s=t|_A^\alpha = T$ iff $|s|_A^\alpha=|t|_A^\alpha$ i.e. they share the same semantic value and represent the same object </li>
</ul>
<h3 id="natural-deduction-2-5">Natural Deduction 2.5</h3>
<p>We don&#39;t have much else to add alongside $=$, and the new rules we use are among the most intuitive of the lot.</p>
<center>
$
\begin{array}{c|c|c}
\textbf{} &amp; \textbf{Introduction} &amp; \textbf{Elimination} \\ \hline
= &amp; [a = a]
  &amp;  \begin{array}{c}
      \begin{array}{cc}\Phi[s/v] &amp; s=t \end{array}   \\ \hline 
      \Phi[t/v]  \\ 
      \end{array}  \\ 
      \end{array}
$
</center>

<ul>
<li>For all constants $a$, it is clear that $a$ is identical to itself, so the introduction rule allows us to say that whenever we want for any constant</li>
<li>If $s$ and $t$ are identical, they can be swapped freely in formulas without hurting the underlying semantics, so the elimination rule also makes sense</li>
</ul>
<p>Using these rules along side our normal natural deduction, try to prove that $=$ is an <strong>equivalence relation</strong>, that is</p>
<ul>
<li>It is reflexive: $\vDash \forall x (x=x)$</li>
<li>It is symmetric: $\vDash \forall x \forall y (x=y \rightarrow y=x)$</li>
<li>It is transitive: $\vDash \forall x \forall y \forall z (x = y \wedge y = z \rightarrow x = z)$</li>
</ul>
<p>just as we would expect of normal identity.</p>
<h3 id="numerical-quantifiers-and-definite-descriptions">Numerical Quantifiers and Definite Descriptions</h3>
<p>With identity in place, we can now establish a surprising amount of additional, useful claims regarding the specifity of the objects we are talking about.</p>
<h4 id="numerical-claims">Numerical Claims</h4>
<p>If we wanted to say, &quot;There is <strong>at least</strong> 1 chicken&quot;, we can already do that with $\exists$ by letting $|P| = \textrm{&quot;…is a chicken&quot;}$ and the formalization $\exists x Px$. This is by definition of what it takes to satisfy $\exists$: it requires only one variable assignment, i.e. object in the domain, to be in the set of chickens that $P$ expresses.</p>
<p>If we want to say there are at least two chickens, then we can write there are two things that are chickens i.e. $\exists x \exists y(Px \wedge Py)$. But this alone does not guarantee there might be two chickens, since if there is one chicken, then the variable assignment where both $x$ and $y$ both refer to the same chicken would satisfy that sentence. So we add the clause that they are distinct: $\exists x \exists y(Px \wedge Py \wedge \neg x = y)$; the $\neg x = y$ prevents our variable assignments allowing $x$ and $y$ to be the same if we want </p>
<p>At least 3 chickens would be like $\exists x \exists y \exists z(Px \wedge Py \wedge Pz \wedge \neg x = y \wedge \neg x = z \wedge \neg y = z)$. <strong>At least $n$ chickens</strong>, would be $\exists x_1 \exists x_2 \cdots \exists x_n(\bigwedge_{i=1}^n Px_i \wedge\bigwedge_{1 \leq i &lt; j \leq n} \neg x_i = x_j)$ where $x_i$ are variables and $\bigwedge$ is like $\sum$ where each term instead of being added is linked by the $\wedge$ connective.</p>
<p>Similarly, if we want <strong>at most</strong> 1 chicken, that is the same as saying the opposite of at least 2 chickens; the complement of $\geq 2$ is $$&lt;2$$ or $\leq 1$. So we can just negate our sentence from before: $\neg \exists x \exists y(Px \wedge Py \wedge \neg x = y)$. A cleaner (and more intuitive way) to formalize this, in my opinion is the following: $\forall x \forall y(Px \wedge Py \rightarrow x = y)$; for every 2 supposedly different chickens, they are actually the same.</p>
<p>At most 2 chickens would be $\forall x \forall y \forall z(Px \wedge Py \wedge Pz \rightarrow x = y \vee x = z \vee y = z)$; if there are 3 supposedly different chickens, actually at least 1 is a duplicate of the other 2. For <strong>at most $n$ chickens</strong>: $\forall x_1 \forall x_2 \cdots \forall x_{n+1}(\bigwedge_{i=1}^{n+1} Px_i \rightarrow \bigvee_{1\leq i &lt; j \leq n+1} x_i = x_j)$</p>
<h4 id="definite-descriptions">Definite Descriptions</h4>
<p>We can set lower bounds on how many chickens there are, and upper bounds on how many chickens there are, so we are now in place to formalize when there is <strong>exactly one chicken</strong>. For there to be only one supreme chicken, we just need to specify <span style="color:blue">there is at least one</span> and <span style="color:red">at most one</span> chicken: $\color{blue}{\exists x Px} \wedge \color{red}{\forall x \forall y(Px \wedge Py \rightarrow x = y)}$. An even nicer expression is $\exists x (Px \wedge \forall y (Py \rightarrow y = x))$; there is something that is a chicken, and all other chickens are really the same as that original, defining chicken.</p>
<p>With this, we can now formalize <strong>definite descriptions</strong>. When we mention &quot;The president of the United States&quot;, we are referring to a general position i.e. many people were president from George Washington to Joe Biden. However, there is only one <em>current</em> president of the U.S., and we are now able to differentiate the two with our formalizations above. &quot;The president is a democrat&quot; would be written as $\exists x (Px \wedge \forall y (Py \rightarrow y = x) \wedge Qx)$ where $P$ expresses &quot;…is the president of the U.S.&quot; and $Q$ for &quot;…is a democrat&quot;. In general to express, &quot;The $\Phi$ has the property $\Psi$,&quot; we could use the following formula:</p>
<p><strong>Russell&#39;s theory of definite descriptions:</strong> $\exists x (\Phi \wedge \forall y (\Phi[y/x] \rightarrow y = x) \wedge \Psi)$</p>
<p>With definite descriptions in hand, we can now formally prove arguments that naturally make sense in English. &quot;Tim&#39;s car is red. Therefore there is a red car.&quot; Easy enough to see in English, but requires a bit more work to express in $\mathcal{L}_=$:</p>
<center>
$\exists x(Px \wedge Qax \wedge \forall y (Py \wedge Qay \rightarrow y = x) \wedge Rx) \vdash \exists (Px \wedge Rx)$ </br></br>

$\begin{align}
a: \ &amp; \textrm{Tim} \
\newline
P: \ &amp; \textrm{…is a car} \
\newline
Q: \ &amp; \textrm{…owns…} \
\newline
R: \ &amp; \textrm{…is red} \
\end{align}$
</center>

<h4 id="generalized-numerical-quantifiers">Generalized Numerical Quantifiers</h4>
<p>We were able to specify <strong>exactly 1</strong> thing satisfies a property, but we can generalize to <strong>exactly $n$</strong> with a simple recursive definition. To express there are exactly $n$ things satisfying a formula, we will denote it with $\exists!_n$, given by the following definition:</p>
<ul>
<li>$\exists!_0 v \Phi = \neg \exists v \Phi$</li>
<li>$\exists!_{n+1} v \Phi = \exists u (\Phi[u/v] \wedge \exists!_n v(\Phi \wedge \neg u = v))$</li>
</ul>
<p>Exactly 0 things satisfy the formula $\Phi$ when there does not exist anything that satisfies it. Exactly $n+1$ things satisfy $\Phi$ when there is something that satisfies $\Phi$ and exactly $n$ <em>distinct, other</em> things that satisfy $\Phi$ as well. As a gut check, we can test to see if this agrees with our definition from definite descriptions from before.</p>
<center>
$\begin{align}
\exists!_1 x Px &amp; = \exists x(Px \wedge \exists!_0 y (Py \wedge \neg y = x)) \
\newline
&amp; \equiv \exists x(Px \wedge \neg \exists y (Py \wedge \neg y = x)) \
\newline
&amp; \equiv \exists x(Px \wedge \forall y \neg (Py \wedge \neg y = x)) \
\newline
&amp; \equiv \exists x(Px \wedge \forall y (\neg Py \vee y = x)) \
\newline
&amp; \equiv \exists x(Px \wedge \forall y (Py \rightarrow y = x)) \
\end{align}$
</center>

<p>By a series of logical equivalences, we can see that we get precisely what we expect.</p>
<h3 id="a-quick-aside-on-identity">A Quick Aside on Identity</h3>
<p>We&#39;ve been using identity loosely so far, since what we mean by &quot;identical&quot; actually varies, whether you realize it or not.</p>
<p>If we say my friend and I have identical cars, we don&#39;t mean that my friend and I literally own the same car, but rather the make, the model, the color, etc. all look identical. This is an example of (approximate) <strong>qualitative identity</strong>, where two objects share the same properties. However, if you say the police tell you your car is the same one that was seen at a crime scene, then we mean it is literally <em>the one and the same</em> car. This is <strong>numerical identity</strong>.</p>
<p>We have to be careful about this since these two types of identities clearly seem disparate. While numerical identity seems to imply qualitative identity (one thing will always share the same properties as itself), it is debated if qualitative identity really implies numerical identity. If two things really share <em>all</em> the same properties, it becomes unclear whether or not that really implies we are talking of the same object.</p>
<p>The language of $\mathcal{L}_=$ focuses on the latter numerical identity, even though the former might be the more convenient one in everyday speech.</p>
<h2 id="summary-of-our-logics">Summary of our Logics</h2>
<p>We&#39;ve covered a lot, so let&#39;s quickly recap some of the key ideas covered so far:</p>
<ul>
<li>Logic studies valid arguments; what conclusions can we draw by nature of the structure of our argument?</li>
</ul>
<p>For $\mathcal{L}_1$:</p>
<ul>
<li>We had basic sentence letters, which we made more complex with the connectives $\{\wedge, \vee, \neg, \rightarrow, \leftrightarrow\}$, each with their own set of truth rules</li>
<li>We modelled the universe in the manner of structures, saying which sentences we said to be true and which to be false</li>
<li>Alongside it came its own proof system, natural deduction, that allowed us to validate arguments in a more systematic way beyond brute force checking</li>
</ul>
<p>For $\mathcal{L}_2$:</p>
<ul>
<li>We lacked the nuance of relating objects to each other in $\mathcal{L}_1$, so we introduced constants to formalize those objects with properties stored as predicates</li>
<li>We updated our model of the universe with specifying constants and predicates (unary, binary, ternary, and n-ary relations)</li>
<li>The universal $\forall$ and existential $\exists$ quantifiers were a nice shortcut to state claims of how many things in the domain satisfy a formula</li>
<li>We updated our proof system to account for these quantifiers</li>
</ul>
<p>For $\mathcal{L}_=$:</p>
<ul>
<li>The notion of numerical identity leads to obvious truths that would be convenient to introduce</li>
<li>We expanded $\mathcal{L}_2$: with the new binary predicate $=$ to show when two constants are essentially the same despite being written with different letters</li>
<li>Included the final set of rules for natural deduction to accommodate $=$</li>
<li>Could now make numerical claims </li>
</ul>
<p>This completes everything you need to know about first-order logic (more on this later), sometimes referred to as <strong>predicate calculus</strong>.</p>
<h1 id="part-2-introduction-to-metatheory">Part 2: Introduction to Metatheory</h1>
<p>What we&#39;ve covered before gives us a pretty reliable way to analyze English arguments, which philosophers really want to make sure they aren&#39;t tripping over themselves when discussing and debating ideas. But there are a whole host of patterns and results <em>within logic itself</em> that arguably have a bigger impact on the rest of science and deductive reasoning.</p>
<p>For example, consider the following theorem:</p>
<hr>
<p><strong><span id="deduction-thm">Deduction Theorem</span>:</strong> $\Gamma, \Psi \vDash \Phi$ if and only if $\Gamma \vDash \Psi \rightarrow \Phi$.</p>
<p>By thinking through the definitions and terms we are working with, we can treat this almost as we would a mathematical theorem, and prove it analytically.</p>
<p><strong>Proof:</strong> If $\Gamma, \Psi \vDash \Phi$, then by consistency (and definition of entailment), $\Gamma, \Psi, \neg \Phi \vDash $. Note that ony whenever the set $\{\Psi, \neg \Phi\}$ is satisfied, so is $\Psi \wedge \neg \Phi$. So we can rewrite our sequent as an equivalent one as $\Gamma, \Psi \wedge \neg \Phi \vDash$. By logical equivalence, then $\Gamma, \neg(\Psi \rightarrow \Phi) \vDash $. Then by consistency again, we arrive at $\Gamma \vDash \Psi \rightarrow \Phi$. $\blacksquare$</p>
<hr>
<p>We are able to determine a result about arguments <em>in general</em>. We don&#39;t know what our premises and conclusion are, yet we can still make substantive claims regarding logical arguments of that form.</p>
<p>Here is another simple example that is commonly used all throughout science and math:</p>
<hr>
<p><strong>Contraposition:</strong> $\Phi \vDash \Psi$ if and only if $\neg \Psi \vDash \neg \Phi$.</p>
<p>&quot;If it is Monday, then I have math class. So if I don&#39;t have math class, it certainly cannot be Monday.&quot; That is the general idea of argument by contraposition: if we know what premise entails a conclusion, and we don&#39;t observe the conclusion, the premise must not be fulfilled either.</p>
<p><strong>Proof:</strong> Suppose $|\neg \Psi|_A = T$. Then $|\Psi|_A = F$. Since $\Phi \vDash \Psi$, then $|\Phi|_A = F$ too since if it didn&#39;t we would break our assumption of enatilment. Thus $|\neg \Phi|_A = T$. We made no assumptions about the structure $A$, and thus found whenever $|\neg \Psi|_A = T$, then also $|\neg \Phi|_A = T$. By the definition of entailment, $\neg \Psi \vDash \neg \Phi$.</p>
<!-- Can also prove by contradiction: ¬Ψ ⊨ Φ ⊨ Ψ #, which clearly cannot happen. So it must be that ¬Ψ ⊨ ¬Φ since every structure assigns a truth value to every sentence. -->
<hr>
<p>We&#39;ve already proven two useful theorems! Now, we will develop and practice using more tools to argue with logic as its own field of study rather than just an auxiliary field to other sciences.</p>
<h2 id="principle-of-mathematical-induction">Principle of Mathematical Induction</h2>
<p>The major tool we will need is induction. For a hypothesis $\Phi$, the <a href="http://xperimex.com/blog/real-induction/"><strong>Principle of Mathematical Induction (PMI)</strong></a> is usually stated as:</p>
<center>
$
\begin{align}
&amp; \Phi(0) 
\newline
&amp; \forall n (\Phi(n) \rightarrow \Phi(n+1))
\newline \hline
&amp; \forall n \Phi(n)
\end{align}
$
</center>

<p>The common analogy is with dominoes: if you knock over a starting domino (show hypothesis $\Phi$ works for integer like 0), and can prove that each domino will knock over the next domino (i.e. the hypothesis holding for $\Phi(n)$ implies the hypothesis holds for $\Phi(n+1)$), then you can infer that all the dominoes will fall over eventually (the hypothesis holds for all integers $\forall n \Phi(n)$).</p>
<hr>
<p>Here is a classic example: we will show the formula for the sum of the first $n$ integers is $\sum_{k=1}^n k = \frac{n(n+1)}{2}$.</p>
<p><strong>Base Case:</strong> The formula holds for $n=1$ since $\sum_{k=1}^1 k = 1 = \frac{1(1+1)}{2}$.</p>
<p><strong>Inductive Hypothesis:</strong> Let&#39;s assume our formula works for the first $n$ integers. We want to show that it holds for case $n+1$: $\sum_{k=1}^{n+1} k = \sum_{k=1}^{n} k + (n+1)$. By our assumption, we can reduce this to $\frac{n(n+1)}{2} + n+1$. Simplifying further, </p>
<center>
$
\begin{align}
\frac{n(n+1)}{2} + n+1 &amp; = \frac{n(n+1) + 2(n+1)}{2}
\newline
&amp; = \frac{(n+1)(n+2)}{2}
\end{align}
$
</center>

<p>Which is precisely the formula our hypothesis predicted. So by the PMI, for all $n$, $\sum_{k=1}^n k = \frac{n(n+1)}{2}$.</p>
<hr>
<p>Those who are more familiar with math will have seen examples of induction everywhere, and it is quite good for proving theorems and claims that naturally divide into these cases-by-integers.</p>
<p>One drawback of induction is that it does not tell you <em>how</em> you get your hypothesis to begin with. That usually requires trial-and-error with a strong intuition, but once you have it, induction gives a relatively straightforward way of proving your claim (if it is right).</p>
<p>The formulation above is sometimes referred to as <strong>weak induction</strong>. The alternative is <strong>strong induction</strong>:</p>
<center>
$
\begin{align}
&amp; \Phi(0) 
\newline
&amp; \forall n (\forall k \leq n \ \Phi(k) \rightarrow \Phi(n+1))
\newline \hline
&amp; \forall n \Phi(n)
\end{align}
$
</center>

<p>Sometimes you need more cases besides just $\Phi(n)$ to prove $\Phi(n+1)$, so strong induction is a way to justify that. Despite the names, the weak and strong forms of induction are equivalent, so we can use either whenever.</p>
<p>With induction in hand, we can now start proving results within logic.</p>
<hr>
<p><strong>Example:</strong> Any $\mathcal{L}_1$ sentence $\Phi$ that only uses the connective $\leftrightarrow$ is not a contradiction i.e. there&#39;s a structure $A$ in which $|\Phi|_A = T$.</p>
<p><strong>Proof:</strong> We will show this by giving a specific structure that $\Phi$ is true, and proving it holds via induction. I propose the structure $A$ where all sentence letters in $\Phi$ are assigned true. That is $\forall \alpha \in \textrm{SenLett}(\Phi) \ |\alpha|_A = T$.</p>
<p><strong>Base Case:</strong> The simplest possible sentence using just $\leftrightarrow$ is the one not using it at all: a sentence letter. So if $\Phi$ is a sentence letter, by construction of our structure, $|\Phi|_A = T$.</p>
<p><strong>Inductive Hypothesis:</strong> We&#39;ll induct on the <strong>complexity</strong> of $\Phi$. So let&#39;s build up $\Phi$ from &quot;simpler&quot; sentences; $\Phi = \Psi_1 \leftrightarrow \Psi_2$ where $\Psi_1, \Psi_2$ are both subsentences only containing $\leftrightarrow$. Remember, we have defined our structure $A$ such that $\forall \alpha \in \textrm{SenLett}(\Phi) \ |\alpha|_A = T$. Since $\Psi_1,\Psi_2$ build up $\Phi$, it should be clear that $\textrm{SenLett}(\Psi_{1,2}) \subseteq \textrm{SenLett}(\Phi)$. Then, by our structure, $\forall \alpha \in \textrm{SenLett}(\Psi_{1,2}) \ |\alpha|_A = T$. By our inductive hypothesis then, $|\Psi_1|_A = |\Psi_2|_A = T$, since they are $\mathcal{L}_1$ sentences that only use $\leftrightarrow$. By the truth table for $\leftrightarrow$, $|\Phi|_A = T$. $\blacksquare$</p>
<p>So for all sentences that only use $\leftrightarrow$, there is a structure in which it is true, and hence it is not a contradiction.</p>
<hr>
<p>Induction naturally lends itself to proofs that are divided by integer cases, and we leveraged that by ascribing a natural number to a sentence via its complexity. Also note we used the strong form of induction here, since we don&#39;t actually know the complexity of $\Psi_1$ or $\Psi_2$, only that they are less complex than the inductive hypothesis necessitates. Here are some more formal definitions of what was used above, and others that will be helpful later:</p>
<ul>
<li>$\textrm{NConn}(\Phi)$: The number of occurrences of connectives in $\Phi$. We also define this as the <strong>complexity</strong> of $\Phi$, as it characterizes how &quot;deep&quot; subsentences go.</li>
<li>$\textrm{Conn}(\Phi)$: The set of connectives used in $\Phi$; $\textrm{NConn}$ counts tokens, while $\textrm{Conn}$ counts types.</li>
<li>$\textrm{SenLett}(\Phi)$: The set of sentence letters in $\Phi$.</li>
<li>$\textrm{Atoms}(\Phi)$: The set of atomic objects in our language.</li>
</ul>
<p>In general, $\textrm{Atoms}(\Phi) = \textrm{SenLett}(\Phi)$ for $\mathcal{L}_1$, but sometimes we will consider convenient extensions of $\mathcal{L}_1$. For one, it&#39;s sometimes useful to have a symbol for tautologies $\top$ and contradictions $\bot$. Just for clarity, for all structures $A$, $|\top|_A = T$ and $|\bot|_A = F$. These are considered useful atoms in the extended language $\mathcal{L}_1^+$.</p>
<p>Here&#39;s another example of how induction can be applied to logic:</p>
<hr>
<p><strong><span id="demorgans">De Morgan&#39;s Laws</span>:</strong> For sentences $\varphi_1, \varphi_2, \cdots, \varphi_n$,</p>
<center>
$\neg (\varphi_1 \wedge \varphi_2 \wedge \cdots \wedge \varphi_n) \equiv \neg \varphi_1 \vee \neg\varphi_2 \vee \cdots \vee \neg\varphi_n$
$\neg (\varphi_1 \vee \varphi_2 \vee \cdots \vee \varphi_n) \equiv \neg \varphi_1 \wedge \neg\varphi_2 \wedge \cdots \wedge \neg\varphi_n$
</center>

<p>For those who are familiar with some set theory, these are identical to how set intersections (equivalent to $\wedge$) and unions (equivalent to $\vee$) relate to each other with complements ($\neg$).</p>
<p><strong>Base Case:</strong> It can easily be seen by truth tables, or verified with natural deduction that $\neg(\varphi_1 \wedge \varphi_2) \equiv \neg\varphi_1 \vee \neg\varphi_2$ (even in English, it can be seen to be fairly reasonable).</p>
<p><strong>Inductive Hypothesis:</strong> Assume this holds for $n$ sentences. Then:</p>
<center>
$
\begin{align}
\neg (\varphi_1 \wedge \cdots \wedge \varphi_n \wedge \varphi_{n+1}) = \neg ((\varphi_1 \wedge \cdots \wedge \varphi_n) \wedge \varphi_{n+1}) &amp; \equiv \neg(\varphi_1 \wedge \cdots \wedge \varphi_n) \vee \neg \varphi_{n+1} \\
&amp; \equiv \neg \varphi_1 \vee \cdots \vee \neg \varphi_n \vee \neg \varphi_{n+1}
\end{align}
$
</center>

<p>The first equivalence is given by the case for 2 sentences, and the last is given by the case for $n$ sentences by the inductive hypothesis. The second law follows similarly. $\blacksquare$</p>
<hr>
<p>The last immediate example we&#39;ll look at is a simple, yet important lemma.</p>
<p><strong>Relevance Lemma:</strong> Suppose for two structures $A$ and $B$, $\forall \alpha \in \ \textrm{Atoms}(\Phi)$ we have it such that $|\alpha|_A = |\alpha|_B$. Then $|\Phi|_A = |\Phi|_B$.</p>
<p>The idea is that the only information pertinent to a logical sentence is what it looks like at the &quot;lowest level&quot;; only the sentence letters in $\Phi$ are what affect its truth value, and nothing else is necessary.</p>
<p><strong>Proof:</strong> We&#39;ll follow similarly before by inducting on the complexity of $\Phi$. </p>
<p><strong>Base Case:</strong> The simplest sentence $\Phi$ can be is a sentence letter. Then by the definition of structures, clearly $|\Phi|_A = |\Phi|_B$. In the case of $\mathcal{L}_1^+$, $\Phi$ can be $\top$ or $\bot$, but since their semantics are fixed for any structure, the claim still holds.</p>
<p><strong>Inductive Hypothesis:</strong> Say this holds for sentences of complexity less than or equal to $n$. Now let $\Phi$ be a sentence of complexity $n+1$ i.e. $\textrm{NConn}(\Phi) = n+1$. Then $\Phi$ is of the form $\neg \Psi_1$, $\Psi_1 \wedge \Psi_2$, $\Psi_1 \vee \Psi_2$, $\Psi_1 \rightarrow \Psi_2$, or $\Psi_1 \leftrightarrow \Psi_2$ where $\textrm{NConn}(\Psi_{1,2}) \leq n$ and $\textrm{NConn}(\Psi_1) + \textrm{NConn}(\Psi_2) = n + 1$. If structures $A$ and $B$ agree on the values of the atoms of $\Phi$, they agree on the atoms of $\Psi_1$ and $\Psi_2$. By the inductive hypothesis, $|\Psi_1|_A = |\Psi_2|_B$. Since the truth value of $\Phi$ is fixed by the truth value of $\Psi_{1,2}$, then in all the cases, by their respective truth tables, $|\Phi|_A = |\Phi|_B$. $\blacksquare$</p>
<p>The Relevance Lemma essentially gives us a way of justifying finite truth tables; the reason why we know the sentence $P \wedge Q$ only depends on the truth values for $P$ and $Q$ is precisely because of the Relevance Lemma; so long as two structures agree on the value of $P$ and $Q$, they will agree on $P \wedge Q$ regardless of what the other sentence letters are assigned. It seems like an obvious fact, but is one that needs to be proven anyway.</p>
<p>Induction, especially on the complexity of sentences, will be a key tool in future results.</p>
<h2 id="truth-functions">Truth Functions</h2>
<p>For future convenience, we&#39;ll introduce the idea of a <strong>truth function</strong>. Just as you&#39;d imagine, truth functions are like the typical function in math that takes some amount of inputs and spits out a single output. We thus define a truth function as a function $f: \{T,F\}^n \rightarrow \{T,F\}$. We have already seen some simple truth functions in the form of connectives. For example, $\wedge$ has the truth function such that $f_\wedge(T,F) = F$; if you connect a true sentence letter with a false sentence letter by $\wedge$, we get a more complex sentence that evaluates to false.</p>
<p>This leads to the natural idea of <strong>sentences expressing truth functions</strong>. We say a sentence $\Phi$ expresses a truth function $f$ iff the sentence letters $P_1,\cdots,P_n$ occur in $\Phi$, and $f(|P_1|_A, \cdots, |P_n|_A) = |\Phi|_A$. </p>
<h2 id="substitution">Substitution</h2>
<p>Earlier we discussed substitution briefly in the context of constants and variables with $\forall$ and $\exists$ and their proof rules. We can generalize substitution even further:</p>
<p><strong>Definition</strong>: For a set of sentences $\Gamma$, $\Gamma[\varphi/S]$ is the uniform subsitution of the sentence $\varphi$ for the sentence letter $S$ in every sentence in $\Gamma$. If $S$ does not occur at all in $\Gamma$, then $\Gamma[\varphi/S] = \Gamma$.</p>
<p>For example, if we have the sentence $\Phi = P \rightarrow (Q \vee R) \wedge P$, then with substitution, $\Phi[(R \leftrightarrow \neg Q) / P] = (R \leftrightarrow \neg Q) \rightarrow (Q \vee R) \wedge (R \leftrightarrow \neg Q)$. This applies for sets of sentences as described above.</p>
<p>We then have the following theorem:</p>
<p><strong>Substitution Theorem:</strong> If $\Gamma \vDash \Phi$, then $\Gamma[\varphi/S] \vDash \Phi[\varphi/S]$.</p>
<p>Which should sort of make sense; we&#39;ve been focusing on the validity of argument as something intrinsic to the <em>structure</em> of the argument, as opposed to having anything to do with the specific sentences. So exchanging sentences with another in an argument should be no issue, even if the sentences are more complicated. We&#39;ll first prove a helpful lemma:</p>
<hr>
<p><strong>Substitution Lemma:</strong> For a sentence $\Psi$, sentence letter $X$, and a structure $A$, we define a new substitution structure $A_{\Psi/X}$ as follows:</p>
<center>

$$ A_{\Psi/X}(\gamma) = \begin{cases} |\Psi|_A \ \textrm{iff} \ \gamma = X  \\ |\gamma|_A  \ \textrm{iff} \ \gamma \neq X \end{cases} $$

</center>

<p>That is, the structure keeps all sentence letters fixed, UNLESS it is $X$, which we assign the value of $\Psi$. Then for all sentences $\Phi$, we have $|\Phi[\Psi/X]|_A = |\Phi|_{A_{\Psi/X}}$.</p>
<p><strong>Proof:</strong> We&#39;ll do this by induction on the complexity of $\Phi$ as usual.</p>
<p><strong>Base Case:</strong> Simplest sentence is a sentence letter. Then by construction of $A_{\Psi/X}$, $|\Phi|_{A_{\Psi/X}} = |\Phi[\Psi/X]|_A$.</p>
<p><strong>Inductive Hypothesis:</strong> Suppose this holds for sentences of complexity $n$. Let $\Phi$ be of complexity $n+1$. Then $\Phi$ is of the form $\neg \delta_1$, $\delta_1 \wedge \delta_2$, $\delta_1 \vee \delta_2$, $\delta_1 \rightarrow \delta_2$, or $\delta_1 \leftrightarrow \delta_2$ where $\textrm{NConn}(\delta_{1,2}) \leq n$ and $\textrm{NConn}(\delta_1) + \textrm{NConn}(\delta_2) = n + 1$. We can then check this by each case.</p>
<p><strong>$\underline{\Phi = \neg \delta}$:</strong> 
$|\Phi|_{A_{\Psi/X}} = |\neg \delta|_{A_{\Psi/X}} = \color{red}{f_{\neg}(|\delta|_{A_{\Psi/X}}) = f_{\neg}(|\delta[\Psi/X]|_A)} = |\neg \delta[\Psi/X]|_A = |\Phi[\Psi/X]|_A$</p>
<p><strong>$\underline{\Phi = \delta_1 \wedge \delta_2}$:</strong> 
$
\begin{align}
|\Phi|_{A_{\Psi/X}} = |\delta_1 \wedge \delta_2|_{A_{\Psi/X}} = \color{red}{f_{\wedge}(|\delta_1|_{A_{\Psi/X}}, |\delta_2|_{A_{\Psi/X}})} \ &amp; \color{red}{= f_{\wedge}(|\delta_1[\Psi/X]|_{A}, |\delta_2[\Psi/X]|_{A})} \\
&amp;  = |\delta_1[\Psi/X] \wedge \delta_2[\Psi/X]|_A \\
&amp; = |(\delta_1 \wedge \delta_2)[\Psi/X]|_A \\
&amp; = |\Phi[\Psi/X]|_A
\end{align}
$</p>
<p>The equality in <span style = "color:red">red</span> is given by the inductive hypothesis, and the rest by definitions of the connectives&#39; truth functions and substitution. The other cases are all identical. $\blacksquare$</p>
<hr>
<p>We can now prove the Substitution Theorem.</p>
<p><strong>Proof</strong>: Suppose for contradiction that $\Gamma \vDash \Phi$ while $\Gamma[\varphi/S] \nvDash \Phi[\varphi/S]$. That is, there is a structure where $A$ where $\forall \gamma \in \Gamma \ |\gamma[\varphi/S]|_A = T$ while $|\Phi[\varphi/S]|_A = F$.</p>
<p>By the Substitution Lemma, there is another structure $B$ where $|\gamma|_B = |\gamma[\varphi/S]|_A = T$ and $|\Phi|_B = |\Phi[\varphi/S]|_A = F$. But that contradicts our original assumption that $\Gamma \vDash \Phi$. So it must be the case that $\Gamma[\varphi/S] \vDash \Phi[\varphi/S]$. $\blacksquare$</p>
<h2 id="disjunctive-normal-form-and-expressive-adequacy">Disjunctive Normal Form and Expressive Adequacy</h2>
<p>While we have the connectives $\wedge,\vee,\neg,\rightarrow,\leftrightarrow$, there&#39;s a natural question as to whether or not we <em>need</em> all of them.</p>
<h4 id="disjunctive-normal-form">Disjunctive Normal Form</h4>
<p>Consider the following sentence: $\neg((P \wedge Q \rightarrow R) \leftrightarrow \neg Q)$. Let&#39;s write out the truth table for this sentence.</p>
<center>
$
\begin{array}{c|c|c|c}
P &amp; Q &amp; R &amp; \neg((P \wedge Q \rightarrow R) \leftrightarrow \neg Q) \\ \hline
\color{red}{T} &amp; \color{red}{T} &amp; \color{red}{T} &amp; \color{red}{T} \\
T &amp; T &amp; F &amp; F \\
T &amp; F &amp; T &amp; F \\
T &amp; F &amp; F &amp; F \\
\color{blue}{F} &amp; \color{blue}{T} &amp; \color{blue}{T} &amp; \color{blue}{T} \\
\color{green}{F} &amp; \color{green}{T} &amp; \color{green}{F} &amp; \color{green}{T} \\
F &amp; F &amp; T &amp; F \\
F &amp; F &amp; F &amp; F \\
\end{array}
$
</center>

<p>This sentence is fairly compact, but also not very readable. We can instead rewrite this sentence into something slightly longer, but logically equivalent that is indicative of what this sentence is saying.</p>
<p>Notice that this sentence is true if and only if one of the three types of structures are in use:</p>
<ol>
<li><span style="color:red">$P,Q,R$ are true</span></li>
<li><span style="color:blue">$P$ is false (or $\neg P$ is true), and $Q,R$ are true</span></li>
<li><span style="color:green">$P$ is false (or $\neg P$ is true), $Q$ is true, and $R$ is false (or $\neg R$ is true)</span></li>
</ol>
<p>These correspond to the <span style="color:red">highlighted rows</span> in the truth table. We can express these truth conditions of the sentence easily then by reading off each condition:</p>
<center>

$\color{red}{(P \wedge Q \wedge R)} \vee \color{blue}{(\neg P \wedge Q \wedge R)} \vee \color{green}{(\neg P \wedge Q \wedge \neg R)}$

</center>

<p>Whenever the <span style="color:red">red structure</span> is in use, then our original sentence is true. Likewise, the first <strong>disjunct</strong> in the above sentence is also true, making the whole sentence true by the truth table for $\vee$. Similarly, when the  <span style="color:blue">blue</span> or  <span style="color:green">green</span> structures are in use, our original sentence is true and so is our new sentence made of just $\neg$, $\wedge$, and $\vee$. And when none of those structures are used, then our original sentence is false, and since our new sentence is made from only the conditions that make our original sentence true, it too would be false. Since these two sentences are true in the same structures and false in all the same structures, these sentences are logically equivalent.</p>
<p>We call this second sentence the <strong>disjunctive normal form</strong> of the original sentence. </p>
<p><strong>Definition:</strong> A sentence is in <strong>disjunctive normal form (DNF)</strong> if it only uses connectives from the set $\{\neg, \wedge, \vee \}$, and that $\vee$ never occurs in the scope of $\neg$ or $\wedge$, and $\wedge$ never occurs in the scope of $\neg$. Informally, a sentence is in DNF if it is a conjunction of disjunctions of sentence letters or their negations.</p>
<p>Our above method gives a constructive way on how to convert sentences into DNF using truth tables. A more formal version of the proof specifying structures is given in Eagle&#39;s <em>Elements of Deductive Logic</em>, but the idea remains the same even if obscured by notation. A sentence $\Phi$ can be written in DNF by writing</p>
<center>

$(\textrm{Case 1} \ \Phi \ \textrm{is true}) \vee (\textrm{Case 2} \ \Phi \ \textrm{is true}) \vee \cdots \vee (\textrm{Case} \ n \ \ \Phi \ \textrm{is true})$

</center>

<p>where each Case is the listing of the truth conditions needed given by the sentence letters.</p>
<p>The alternative to DNF is the <strong>conjunctive nomal form (CNF)</strong>, where you can write a logically equivalent sentence using a conjunction of disjunctions of sentence letters and or their negations. The proof that any sentence can be written in CNF can be done similarly to the proof of DNF. The idea is a sentence $\Phi$ is true if and only if <em>none</em> of the structures that make it <em>false</em> are in use.</p>
<p>But we also can use <a href="#demorgans">De Morgan&#39;s Laws</a> and the existence of DNF to prove the existence of CNF much quicker. First, write $\neg \Phi$ in DNF: $\neg \Phi \equiv \bigvee_{n=1}^m (\bigwedge_{i=1}^k \mathscr{P}_i)$ where $\mathscr{P}_i$ is a sentence letter or its negation. This would say that there are $k$ sentence letters in $\neg \Phi$, and that you only need $m$ disjuncts to express it. But, since $\neg \neg \Phi \equiv \Phi$, we can negate $\neg \Phi$ in DNF to get $\Phi$ in CNF: </p>
<center>

$\Phi \equiv \neg (\neg \Phi) \equiv \neg \bigvee_{n=1}^m (\bigwedge_{i=1}^k \mathscr{P}_i) \equiv \bigwedge_{n=1}^m \neg (\bigwedge_{i=1}^k \mathscr{P}_i) \equiv \bigwedge_{n=1}^m (\bigvee_{i=1}^k \neg \mathscr{P}_i)$

</center>

<p>which is precisely in CNF, with $m$ conjuncts and all the sentence letters and their negations negated.</p>
<h4 id="expressive-adequacy">Expressive Adequacy</h4>
<p>We have seen above that we can convert any sentence into a logically equivalent one using only $\neg$, $\wedge$, and $\vee$. However, note the only thing we really needed was the <em>truth table</em> of a sentence, not the sentence itself. So if we outline <em>any</em> truth function via a truth table, we can find a sentence in DNF that expresses that truth function.</p>
<p>So we say that the set of connectives $\{\neg, \wedge, \vee \}$ is <strong>expressively adequate</strong>: any truth function can be expressed by a sentence using exclusively the connectives $\{\neg, \wedge, \vee \}$. In other words, the truth functions of $\{\neg, \wedge, \vee \}$ can make any other truth function under composition with each other. We proved that with the existence of DNF.</p>
<p>Then, in a way, we have some redundant connectives in $\mathcal{L_1}$: $\rightarrow$ and $\leftrightarrow$ can be expressed using $\{\neg, \wedge, \vee \}$.</p>
<center>
$
\begin{align}
\Phi \rightarrow \Psi &amp; \equiv \neg \Phi \vee \Psi \\
\Phi \leftrightarrow \Psi &amp; \equiv (\neg \Phi \vee \Psi) \wedge (\neg \Psi \vee \Phi)
\end{align}
$
</center>

<p>Of course, it&#39;s much more convenient to use $\rightarrow$ and $\leftrightarrow$ than their equivalent forms, but in a way, they are just that—a convenience.</p>
<p>But we can do better. We know from De Morgan&#39;s Laws:</p>
<center>
$
\begin{align}
\Phi \wedge \Psi &amp; \equiv \neg(\neg \Phi \vee \neg \Psi) \\
\Phi \vee \Psi &amp; \equiv \neg(\neg \Phi \wedge \neg \Psi)
\end{align}
$
</center>

<p>So even $\wedge$ and $\vee$ is redundant; you only need one of them with negation to express the other.</p>
<p>So we have two small expressively adequate sets already with $\{\neg, \vee\}$ and $\{\neg, \wedge\}$, but there are many others, such as $\{\neg, \rightarrow \}$ and $\{ \rightarrow, \bot \}$. There are even single connectives that are expressively adequate. Consider the connectives with the following truth tables:</p>
<center>
$
\begin{array}{c|c|c}
P &amp; Q &amp; (P \uparrow Q) \\ \hline
T &amp; T &amp; F  \\
T &amp; F &amp; T  \\
F &amp; T &amp; T  \\
F &amp; F &amp; T  \\
\end{array}
\ \ \ \ 
\begin{array}{c|c|c}
P &amp; Q &amp; (P \downarrow Q) \\ \hline
T &amp; T &amp; F  \\
T &amp; F &amp; F  \\
F &amp; T &amp; F  \\
F &amp; F &amp; T  \\
\end{array}
$
</center>

<p>$\uparrow$ is sometimes called <strong>nand</strong> (as in not/negated-and) while $\downarrow$ is <strong>nor</strong> (not-or). Since we know $\{\neg, \wedge \}$ is expressively adequate, and that</p>
<center>
$
\begin{align}
\neg \Phi &amp; \equiv \Phi \uparrow \Phi \\
\Phi \wedge \Psi &amp; \equiv (\Phi \uparrow \Psi) \uparrow (\Phi \uparrow \Psi)
\end{align}
$
</center>

<p>so $\{\uparrow \}$ can express the truth functions of the expressively adequate connective set $\{\neg, \wedge \}$. Thus, $\{\uparrow \} $ is expressively adequate. </p>
<p>Here are some good exercises to try and fully wrap your head around expressive adequacy:</p>
<ul>
<li>Show that $\{\downarrow \}$ is expressively adequate as well (hint: try to write another expressively adequate set in terms of just $\downarrow$).</li>
<li>Show $\uparrow$ and $\downarrow$ are the <em>only</em> 2-place connectives that are expressively adequate by themselves.</li>
<li>Consider the 3-place connective $\square(\Phi, \Psi, \Delta)$ which is true iff $\Phi,\Psi,\Delta$ are all false. Show $\{\square\}$ is expressively adequate.</li>
<li>Show $\{\neg\}$ is not expressively adequate (hint: how many inputs can a sentence only using $\neg$ have?)</li>
<li>Show $\{\vee, \wedge, \rightarrow, \leftrightarrow\}$ is not expressively adequate (hint: find a specific truth function it cannot express).</li>
<li>Consider the new connective $\leftrightarrow^*$ with the following truth table:
<center>
$
\begin{array}{c|c|c}
P &amp; Q &amp; (P \leftrightarrow^* Q) \\ \hline
T &amp; T &amp; F  \\
T &amp; F &amp; T  \\
F &amp; T &amp; T  \\
F &amp; F &amp; F  \\
\end{array}
$
</center>
Show $\{\leftrightarrow, \leftrightarrow^*\}$ is not expressively adequate.</li>
</ul>
<h2 id="duality">Duality</h2>
<p>We have seen many times that there&#39;s a natural interplay between between $\wedge$ and $\vee$ with patterns of negation with <a href="#demorgans">De Morgan&#39;s Laws</a>,  and as well as between $\forall$ and $\exists$. Even in English, we see this mixing of &quot;internal&quot; and &quot;external&quot; negations; &quot;already outside&quot; means the same thing as &quot;not still inside&quot;, so &quot;already&quot; and &quot;still&quot; act in this &quot;dual&quot; manner, similar to $\wedge$ and $\vee$.</p>
<p>We can formalize logical <strong>duality</strong>, but we first will introduce a new, convenient extension to $\mathcal{L}_1^+$, appropriately called $\mathcal{L}_1^{++}$. This language is exactly like $\mathcal{L_1}^+$, but with the addition of generalized connectives; for each $n$-place truth function $f$, there is a unique $n$-place connective $c$ that is associated with $f$ i.e. that would express it with $n$ sentence letters.</p>
<p>Something else worth noting that I&#39;ve avoided for consistency is that sometimes it&#39;s useful to represent $T$ with 1 and $F$ with 0, so we can do basic arithmetic to simplify our manipulation of truth values. For example, $|\neg P|_A = 1 - |P|_A$, or with $\wedge$, $|P \wedge Q|_A = |P|_A \cdot |Q|_A$.</p>
<p><strong>Definition (Dual of a Connective):</strong> Let $c$ be an $n$-place connective with associated truth function $f_c$. The <strong>dual connective</strong> $c^*$ is the connective with the associated truth function $f_{c^*}$ defined as:</p>
<center>

$f_{c^*}(t_1,t_2,\cdots,t_n) = 1 - f_c(1 - t_1,1-t_2,\cdots,1-t_n)$

</center>

<p>for all truth values $t_1,t_2,\cdots,t_n$.</p>
<p>In essence, the dual connective <em>is defined by</em> this relation of internal and external negations. In our discussion of expressive adequacy, the final problem I wrote at the end used $\leftrightarrow^{*}$, the dual of $\leftrightarrow$. For a more visual definition, the dual of a connective $c^*$ is obtained by flipping every occurrence of $T$ to $F$ and $F$ to $T$ in the truth table for $c$. If we look at $\wedge$, then</p>
<center>
$
\begin{array}{c|c|c}
P &amp; Q &amp; (P \wedge Q) \\ \hline
T &amp; T &amp; T  \\
T &amp; F &amp; F  \\
F &amp; T &amp; F  \\
F &amp; F &amp; F  \\
\end{array}
\Longrightarrow \
\begin{array}{c|c|c}
P &amp; Q &amp; (P \wedge^* Q) \\ \hline
F &amp; F &amp; F  \\
F &amp; T &amp; T  \\
T &amp; F &amp; T  \\
T &amp; T &amp; T  \\
\end{array}
$
</center>

<p>We see then that $\wedge^*$ has the exact same truth table for $\vee$, and conclude they are duals. If we do the same for $\vee$, we would see that $\vee^*$ has the same truth table for $\wedge$, and that leads us to our first observation.</p>
<hr>
<p><strong>Claim:</strong> For all $\mathcal{L}_1^{++}$ connectives, $c^{**} = c$.</p>
<p><strong>Proof:</strong> </p>
<center>

$\begin{align} f_{c^{**}}(t_1,t_2,\cdots,t_n) &amp; = 1 - f_{c^{*}}(1 - t_1,1-t_2,\cdots,1-t_n) \\ &amp; = 1 - (1 - f_c( 1 - (1 - t_1),1-(1-t_2),\cdots,1-(1-t_n))) \\ &amp; = f_{c}(t_1,t_2,\cdots,t_n) \end{align}$

</center>

<p>Since these associated truth functions are unique to each connective, we&#39;ve shown $c^{**} = c$. $\blacksquare$</p>
<hr>
<p>Connective duals are the heart of this topic, so with that solidified, we are now in a position to define other forms of duality:</p>
<p><strong>Definition (Generalized Duality):</strong></p>
<ul>
<li>The <strong>dual of a sentence</strong> is given recursively: if $\Phi$ is a sentence letter, then $\Phi^{*} = \Phi$, and if $\Phi = c(\varphi_1, \cdots, \varphi_n)$, then $\Phi^{*} = (c(\varphi_1, \cdots, \varphi_n))^{*} = c^{*}(\varphi_1^{*}, \cdots, \varphi_n^{*})$</li>
<li>Let $T^* = F$ and $F^* = T$. The <strong>dual of a structure</strong> $A^{*}$ is defined by flipping the truth values of all sentence letters in $A$, i.e. $|\alpha|_{A^*} = (|\alpha|_A)^* = 1 - |\alpha|_A$ for all sentence letters $\alpha$ </li>
</ul>
<p>We can now prove another adjacent lemma as before.</p>
<hr>
<p><strong>Claim:</strong> For all $\mathcal{L}_1^{++}$ sentences, $\Phi^{**} = \Phi$.</p>
<p><strong>Proof:</strong> Induct on the complexity of $\Phi$.</p>
<p><strong>Base Case:</strong> If $\Phi$ is a sentence letter, then $\Phi^{**} = (\Phi^*)^* = \Phi^* = \Phi$.</p>
<p><strong>Inductive Hypothesis:</strong> Suppose this holds for sentences of complexity $n$. Let $c$ be the highest scope connective of $\Phi$ i.e. $\Phi = c(\varphi_1, \varphi_2, \cdots, \varphi_n)$ with $\textrm{NConn}(\varphi_i) \leq n$. Then</p>
<center>

$
\begin{align}
\Phi^{**} = c(\varphi_1, \varphi_2, \cdots, \varphi_n)^{**} = c^*(\varphi_1^*, \varphi_2^*, \cdots, \varphi_n^*)^* &amp; = c^{**}(\varphi_1^{**}, \varphi_2^{**}, \cdots, \varphi_n^{**}) \\ &amp; = c(\varphi_1, \varphi_2, \cdots, \varphi_n) \\ &amp; = \Phi
\end{align}
$
</center>

<center>
$\blacksquare$
</center>

<p>It&#39;s worth mentioning that outside of $\mathcal{L}_1^{++}$, it might not be the case that $\Phi^{**} = \Phi$ since we don&#39;t have this nice general connective $c$ to work with. But, it will still be logically equivalent; they may not look the same in other languages (as in use the exact same characters in the exact same order), but certainly $\Phi^{**} \equiv \Phi$.</p>
<hr>
<p>With all of this in place, we now have our first major result:</p>
<p><strong>Duality Lemma:</strong> For all sentences, $|\Phi^*|_A + |\Phi|_{A^*} = 1$. In other words, $|\Phi^*|_A = |\neg\Phi|_{A^*}$</p>
<p><strong>Proof:</strong> Induct on the complexity of $\Phi$.</p>
<p><strong>Base Case:</strong> If $\Phi$ is a sentence letter, then $|\Phi^{*}|_A = |\Phi|_A = 1 - |\Phi|_{A^*}$</p>
<p><strong>Inductive Hypothesis:</strong> Suppose this holds for sentences of complexity $n$. Let $c$ be the highest scope connective of $\Phi$ i.e. $\Phi = c(\varphi_1, \varphi_2, \cdots, \varphi_n)$ with $\textrm{NConn}(\varphi_i) \leq n$. Then</p>
<center>
$
\begin{align}
|\Phi^*|_A = |c^*(\varphi_1^*,\varphi_2^*,\cdots,\varphi_n^*)|_A &amp; = f_{c^*}(|\varphi_1^*|_A, |\varphi_2^*|_A, \cdots, |\varphi_n^*|_A) \\
&amp; = f_{c^*}(1 - |\varphi_1|_{A^*}, 1 - |\varphi_2|_{A^*}, \cdots, 1 - |\varphi_n|_{A^*}) \\
&amp; = 1 - f_{c}(|\varphi_1|_{A^*}, |\varphi_2|_{A^*}, \cdots, |\varphi_n|_{A^*}) \\
&amp; = 1 - |c(\varphi_1,\varphi_2,\cdots,\varphi_n)|_{A^*} \\
&amp; = 1 - |\Phi|_{A^*}
\end{align}
$
</center>

<p>This lemma comes with a very nice consequence:</p>
<p><strong>Duality Theorem:</strong> If $\Phi \vDash \Psi$, then $\Psi^* \vDash \Phi^*$.</p>
<p><strong>Proof:</strong> Say $|\Psi^*|_A = 1$. Then by the Duality Lemma, $|\Psi|_{A^*} = 0$. Since $\Phi \vDash \Psi$, then $|\Phi|_{A^*} = 0$. By the Duality Lemma again, $|\Phi^*|_A = 1$. So in any structure where $|\Psi^*|_A = 1$, $|\Phi^*|_A = 1$. In other words, $\Psi^* \vDash \Phi^*$.</p>
<p>Some other interesting ideas to consider:</p>
<ul>
<li>We proved earlier that $c^{**} = c$, but that does not rule out the possibility that there are connectives such that $c^* = c$. For example, $\neg$ is <strong>self-dual</strong> as $\neg^* = \neg$. Can you find any other self-dual connectives?</li>
<li>Having shown $\wedge$ and $\vee$ as duals, this gives us a nice informal way to explain why $\forall$ and $\exists$ are duals too (remember, $\forall x Px \equiv \neg \exists x \neg Px$). Informally, $\forall x Px$ sort of expresses $\bigwedge_{\tau \in C} P\tau$ which ranges over all constants $C$ (while accurate, it is not a strictly good way of defining $\forall x Px$ as sentences cannot be of infinite length). Similarly, $\exists x Px$ is sort of equivalent to $\bigvee_{\tau\in C} P\tau$. So given the duality of $\wedge$ and $\vee$, perhaps it is not that surprising that $\forall$ and $\exists$ are duals of each other too.</li>
<li>The Duality Theorem applies to only single sentences entailing other sentences, but what about sets of sentences? We can make a modified version for entailment between sets: we say $\Gamma \vDash \Sigma$ if when all sentences of $\Gamma$ are true, <em>at least one</em> sentence of $\Sigma$ is true. We can then also define $\Gamma^* = \{\gamma^* \ | \ \gamma \in \Gamma \}$ i.e. the dual of a set of sentences is the set of all dual sentences in the set. Then we can also prove in a similar manner if $\Gamma \vDash \Sigma$, then $\Sigma^* \vDash \Gamma^*$.</li>
</ul>
<h1 id="part-3-soundness-and-completeness">Part 3: Soundness and Completeness</h1>
<p>The previous section was an exploration into how we are able to analyze logic in a very robust and formal way akin to the way we do so in math. And to be fair, it did start to feel like we were doing math after a certain point; we were manipulating sentences and structures in a fairly abstract way, while interesting, did not always have a direct appeal to <em>why</em> we were cared about those topics outside of curious questions. We now return back to some more concrete motivations, as we now have the methods to finally break down the two key theorems that make logic useful.</p>
<h2 id="soundness">Soundness</h2>
<p>As mentioned earlier, soundness is basically what makes proof systems and provability useful. As a reminder,</p>
<p><strong>Soundness Theorem:</strong> If $\Gamma \vdash \Phi$, then $\Gamma \vDash \Phi$.</p>
<p>That is, for a given proof system, if it is sound, then it &quot;preserves truth&quot;; you wouldn&#39;t be able to prove something that is a non-sensical, bad argument. Soundness is arguably one of, if not, the most important quality we can have in a logical system. It&#39;s what allows us to know that for any right triangle the square of the shorter legs sum to the hypotenuse without having to check every right triangle. It&#39;s what allows us to know that $\sqrt{2}$ is irrational without having to check every possible fraction.</p>
<p>And the way you prove soundness is surprisingly easy.</p>
<p><strong>Proof:</strong> We will prove this with induction, but instead of looking at the complexity of sentences, we will induct on the <em>complexity of proofs</em>; we will ascribe an integer to a proof to how many natural deduction rules it uses. </p>
<p>It&#39;s also worth noting here that our proof of soundness below <em>only</em> applies to natural deduction; we have to prove soundness for <em>each</em> proof system. We are working with Natural Deduction, so we will show those rules are sound, but if we use another proof system, say, <a href="https://en.wikipedia.org/wiki/Frege%27s_propositional_calculus">Frege&#39;s propositional calculus</a>, we would have to re-prove soundness (since we could just make up arbitrary proof rules that are not sound if we wanted).</p>
<p><strong>Base Case:</strong> The simplest proof of &quot;complexity 0&quot; of $\Phi$ is from $\Phi$ itself $\Phi \vdash \Phi$; if you know $\Phi$, you certainly know $\Phi$ without needing to use any proof rules. Clearly $\Phi \vDash \Phi$ as any structure such that $|\Phi|_A = T$, that structure also assigns $|\Phi|_A = T$, establishing the base case.</p>
<p><strong>Inductive Step:</strong> Now we will assume from premises $\Gamma$ that our proofs are sound, up until the last step. We will check for each of our Natural Deduction rules that they are sound. </p>
<p>$\underline{\wedge\textrm{-Intro:}}$ Suppose we have a proof of $\Psi_1$ from premises $\Pi_1$ (that is, $\Pi_1 \vdash \Psi_1$) and $\Psi_2$ from premises $\Pi_2$ (similarly $\Pi_2 \vdash \Psi_2$), we obtain a proof $\Psi_1 \wedge \Psi_2$ from an application of $\wedge\textrm{-Intro}$ (where $\Pi_1, \Pi_2 \subseteq \Gamma \ $). By our inductive hypothesis, $\Pi_1 \vDash \Psi_1$ and $\Pi_2 \vDash \Psi_2$. So, for any structure that satisfies $\Gamma$, that structure clearly satisfies $\Pi_1$ and $\Pi_2$ (as they come from $\Gamma \ $), and therefore also satisfies $\Psi_1$ and $\Psi_2$ (by the entailment derived from our inductive hypothesis). So $\Gamma \vDash \Psi_1$ and $\Gamma \vDash \Psi_2$. By the truth table for $\wedge$, we can see that $\Gamma \vDash \Psi_1 \wedge \Psi_2$.</p>
<p>$\underline{\wedge\textrm{-Elim:}}$ From a proof of $\Psi_1 \wedge \Psi_2$ on premises $\Gamma$ ($ \ \Gamma \vdash \Psi_1 \wedge \Psi_2$), we obtain a proof of $\Psi_1$ (or $\Psi_2$) using $\wedge\textrm{-Elim}$. By our inductive hypothesis, $\Gamma \vDash \Psi_1 \wedge \Psi_2$. By the truth table for $\wedge$, $\Psi_1 \wedge \Psi_2$ is true iff $\Psi_1$ and $\Psi_2$ are true, so we can conclude $\Gamma \vDash \Psi_1$ and $\Gamma \vDash \Psi_2$.</p>
<hr>
<p>This is the basic idea of proving soundness: use our knowledge of semantics and definitions to show our final entailment. Sometimes it is just a matter of writing out what feels obvious, but some might require some more background knowledge or tricks.</p>
<hr>
<p>$\underline{\textrm{→-Intro:}}$ From a proof of $\Phi$ on premises $\Gamma \cup \{\Psi\}$, get a proof $\Gamma \vdash \Psi \rightarrow \Phi$ with $\textrm{→-Intro}$ (discharging $\Psi$ at the end). From the inductive hypothesis $\Gamma, \Psi \vDash \Phi$. By the <a href="#deduction-thm">Deduction Theorem</a>, $\Gamma \vDash \Psi \rightarrow \Phi$.</p>
<p>$\underline{\textrm{→-Elim:}}$ From a proof of $\Psi$ on premises $\Pi_1$ and another proof of $\Psi \rightarrow \Phi$ from premises $\Pi_2$, obtain a proof of $\Phi$ via $\textrm{→-Elim}$ (where $\Pi_1, \Pi_2 \subseteq \Gamma \ $). By the inductive hypothesis, $\Gamma \vDash \Psi$ and $\Gamma \vDash \Psi \rightarrow \Phi$. By the truth table for $\rightarrow$, whenever $\Gamma$ is satisfied, $\Phi$ must also be satisfied. Thus, $\Gamma \vDash \Phi$.</p>
<p>The other cases for $\neg$, $\vee$, and $\leftrightarrow$ are all very similar (but do know they are in fact sound). $ \ \blacksquare$</p>
<h3 id="soundness-of-mathcal-l-_2-">Soundness of $\mathcal{L}_2$</h3>
<p>The above proof shows the natural deduction proof system is sound in $\mathcal{L}_1$, but we&#39;ve moved on past to bigger and better things. To show natural deduction is sound in $\mathcal{L}_2$, we only need to show the 4 new rules are sound: $\forall\textrm{-Intro}$, $\forall\textrm{-Elim}$, $\exists\textrm{-Intro}$, and $\exists\textrm{-Elim}$.</p>
<p>I won&#39;t go through them in detail (because I this post is long enough and I don&#39;t want to type them out), but the proof idea is exactly the same as it was for $\mathcal{L}_1$. Here&#39;s a rough sketch of the results one could show to deduce soundness of $\mathcal{L}_2$ (starter proofs can be found in <em>Elements of Deductive Logic</em>):</p>
<ol>
<li><strong><u>Substitution of Co-Designating Terms</u>:</strong> Let $\tau_1$ and $\tau_2$ be constants/variables, and $\varphi[\tau_2/\tau_1]$ is the formula of replacing free occurrences of $\tau_1$ by $\tau_2$ where none of these instances fall under $\forall \tau_2$ or $\exists \tau_2$ (constants occur freely vacuously). Then for any structure $A$ and variable assignment $\alpha$ where $|\tau_1|_A^\alpha = |\tau_2|_A^\alpha$, then $|\varphi|_A^\alpha = |\varphi[\tau_2/\tau_1]|_A^\alpha$ (show with induction on the length of formulae). <ul>
<li>This basically says that if two constants/variables stand for the same thing, they are interchangeable in that variable assignment. </li>
</ul>
</li>
<li>With substitution of co-designating terms and the satisfaction rules for $\forall$ and $\exists$, show the following sequents are correct:<ul>
<li>$\Phi[t/v] \vDash \exists v \Phi$</li>
<li>$\forall v \Phi \vDash \Phi[t/v]$</li>
<li>If $\Gamma, \Phi[t/v] \vDash \Psi$, then $\Gamma, \exists v \Phi \vDash \Psi$ where the constant $t$ does not occur in $\Gamma, \Phi, \Psi$</li>
<li>If $\Gamma \vDash \Phi[t/v]$, then $\Gamma \vDash \forall v \Phi$ where constant $t$ does not occur in $\Gamma, \Phi$</li>
</ul>
</li>
<li>Use those sequents to complete the Soundess Theorem for $\forall$ and $\exists$ in the inductive steps of the proof.</li>
</ol>
<h2 id="completeness">Completeness</h2>
<p>We have shown soundness, meaning anything that we do prove is a good argument. But we haven&#39;t really given a method of showing <em>how</em> to prove things; proofs in natural deduction—in math even—often rely on having a good intuition of the problem at hand that can be formalized into rigorous logic. For example, look at the following claim and proof:</p>
<hr>
<p><strong>Claim: There exists irrational numbers $a$ and $b$ such that $a^b$ is rational.</strong></p>
<p><strong>Proof:</strong> Consider the number $\sqrt{2}^\sqrt{2}$. </p>
<ul>
<li>If this is rational, we&#39;re done. </li>
<li>If this is irrational, then consider the number $(\sqrt{2}^\sqrt{2})^\sqrt{2} = \sqrt{2}^2 = 2$, which is rational, and we are done.</li>
</ul>
<p>Never once did we actually deduce the rationality of $\sqrt{2}^\sqrt{2}$, but by exhausting the possible cases, it doesn&#39;t matter since every possibility leads to a conclusion that proves our claim. $ \ \blacksquare$</p>
<hr>
<p>To independently think of the above proof, one would have to just be comfortable and familiar with exponents, since it really just abused the fact how exponenets combine to create a possible number that satisfies the claim. Moreover, the above proof used the implicit, extra premise that all real numbers are either rational or irrational. This might be a tautology that can be proven under what one assumes about the real numbers, but that would still need to be shown (since <a href="http://xperimex.com/blog/constructive-proofs/">not everyone necessarily takes this for granted</a>). All together, this proof requires a lot of creativiity to not only think of the individual, relevant facts, but to string them together too.</p>
<p>What am I getting at, though? Since there is no algorithm or method to go about proofs, we have no good way to determine if we can prove something until we have proved it. When something has <em>not</em> been proven, though, we don&#39;t just give up; mathematicians and scientists keep searching for new techniques and evidence in the hopes of proving or disproving a theorem. But there&#39;s a key word there: &quot;hope&quot;. We don&#39;t actually know if what we are trying to prove, actually <i>is</i> provable! We don&#39;t know if we are wasting our time away on a Sisyphean quest with no end.</p>
<p>Ideally, we want to be working in a <strong>complete logical system</strong>, that is:</p>
<p><strong>Completeness Theorem:</strong> If $\Gamma \vDash \Phi$, then $\Gamma \vdash \Phi$.</p>
<p>This is the converse of soundness, and would be a very convenient property of our logic to have, since it would mean there are no &quot;unjustified&quot; truths; all arguments would have a chain of causal reasoning in our deductive system that allow us to show its validity.</p>
<p>Some of you may have heard of completeness over soundness before for a couple of reasons: 1) soundness is a fairly intuitive property many of us just trust, as much of logic can be readily thought out to seem to make sense; but more likely 2) <a href="https://plato.stanford.edu/entries/goedel-incompleteness/">Gödel&#39;s incompleteness theorems</a> are among the most celebrated and frustrating results of modern math that have infiltrated the highest ranks of science legends. Ultimately, they culminate many decades of the development of logic and putting to rest, arguably the most fundamental question in math: can we know everything? The ultimate answer is <strong>no</strong>, leaving us with many theorems in math that might be logically true, but just unprovable from our axioms. As of now, over <a href="http://numbers.computation.free.fr/Constants/Miscellaneous/zetazeros1e13-1e24.pdf">10 trillion non-trivial zeroes</a> of the Riemann hypothesis have been verified, yet a concrete, irrefutable proof of this 160 year old problem still eludes us, and incompleteness forces us to wonder if there might not be one at all (but <a href="https://en.wikipedia.org/wiki/Divisor_function">if the Riemann hypothesis is false, then it is provably false according to Robin&#39;s theorem!</a>).</p>
<p>But that&#39;s going a bit too far off the beaten path. Fortunately for us, $\mathcal{L}_1$, $\mathcal{L}_2$, and $\mathcal{L}_=$ are all complete logics, and the rest of this section will be to show that, starting with $\mathcal{L}_1$. </p>
<p>Having a complete system is desirable for a few reasons. Having all theorems be provable is of course nice, but completeness also allows us to connect a lot of dots between semantics and proofs as we would expect. Earlier we mentioned the idea of ND-consistency. In a sound and complete system (which ND is), it turns out syntactic consistency is equivalent to semantic consistency (or satisfiability):</p>
<p><strong>Claim:</strong> $\Gamma$ is ND-consistent iff it is satisfiable.</p>
<p><strong>Proof:</strong></p>
<ul>
<li><p>$(\Rightarrow)$ Suppose $\Gamma$ is ND-consistent. Then there is a sentence $\Phi$ such that $\Gamma \nvdash \Phi$. By completeness, $\Gamma \nvDash \Phi$. The only way an argument or sequent is invalid is if there is a structure $A$ such that $A \vDash \Gamma$ but $A \nvDash \Phi$. But then we have a structure such that $A \vDash \Gamma$, thus showing $\Gamma$ is satisfiable.</p>
</li>
<li><p>$(\Leftarrow)$ We&#39;ll prove the contrapositive i.e. we&#39;ll show that if $\Gamma$ is ND-inconsistent, then it is unsatisfiable. So say $\Gamma$ is ND-inconsistent, that is, $\Gamma \vdash \Phi$ for all sentences $\Phi$. By soundness, we have $\Gamma \vDash \Phi$ for all sentences $\Phi$. This includes contradictions, such as $\Phi = P \wedge \neg P$, and the only way $\Gamma$ could entail all sentences, including contradictions, would be if it was unsatisfiable.</p>
</li>
</ul>
<p>From here on, I&#39;ll use consistent only to mean ND-consistent unless I specify otherwise, and use satisfiable for semantic consistency.</p>
<h3 id="deductive-completeness">Deductive Completeness</h3>
<p>Our ultimate goal is to prove completeness of a <em>logical language</em>. But first, we&#39;ll need to talk about the completeness of <em>a set of sentences</em>:</p>
<ul>
<li><strong>Definition (Semantic Completeness):</strong> $\Gamma$ is <em>semantically complete</em> when for all sentences $\Phi$, either $\Gamma \vDash \Phi$ or $\Gamma \vDash \neg \Phi$ (or both)</li>
<li><strong>Definition (Deductive Completeness):</strong> $\Gamma$ is <em>deductively complete</em> when for all sentences $\Phi$, either $\Gamma \vdash \Phi$ or $\Gamma \vdash \neg \Phi$ (or both)</li>
</ul>
<p>Semantically complete sets are like structures, ascribing truth values to all sentences when it is satisfied. Deductively complete sets act likewise but with proofs. </p>
<p>Combining ND-consistency and ND-completeness allows us to prove a very intuitive result about proofs:</p>
<hr>
<p><strong>Consistency and Completeness Lemma:</strong> Suppose $\Gamma \subseteq \textrm{Sen}(\mathcal{L}_1)$ is ND-consistent and -complete. Then for all sentences $\Phi,\Psi$:</p>
<ol type="i">
  <li>$\Gamma \vdash \neg \Phi$ iff $\Gamma \nvdash \Phi$ </li>
  <li>$\Gamma \vdash \Phi \wedge \Psi$ iff $\Gamma \vdash \Phi$ and $\Gamma \vdash \Psi$</li>
  <li>$\Gamma \vdash \Phi \vee \Psi$ iff $\Gamma \vdash \Phi$ or $\Gamma \vdash \Psi$ (or both)</li>
  <li>$\Gamma \vdash \Phi \rightarrow \Psi$ iff $\Gamma \nvdash \Phi$ or $\Gamma \vdash \Psi$ (or both)</li>
  <li>$\Gamma \vdash \Phi \leftrightarrow \Psi$ iff $\Gamma \vdash \Phi$ and $\Gamma \vdash \Psi$, or $\Gamma \nvdash \Phi$ and $\Gamma \nvdash \Psi$</li>
</ol>

<p>This lemma esentially allows us to formalize results about proofs in how we would expect them to act; it gives us a bridge that consistency and completeness are enough to show that proofs and derivability act like <a href="#satisfaction-and-truth-in-mathcal-l-_2-">truth in a structure</a>.</p>
<p><strong>Proof:</strong> We&#39;ll just verify each case individually.</p>
<p><u><strong>Case (i)</u>:</strong></p>
<ul>
<li>$(\Rightarrow)$ Say $\Gamma \vdash \neg \Phi$. By its ND-consistency, $\Gamma \nvdash \Phi$.</li>
<li>$(\Leftarrow)$ Say $\Gamma \nvdash \Phi$. By its ND-completeness, $\Gamma \vdash \neg \Phi$.</li>
</ul>
<p><u><strong>Case (ii)</u>:</strong></p>
<ul>
<li>$(\Rightarrow)$ If $\Gamma \vdash \Phi \wedge \Psi$, then by $\wedge$-Elim, $\Gamma \vdash \Phi$ and $\Gamma \vdash \Psi$.</li>
<li>$(\Leftarrow)$ If $\Gamma \vdash \Phi$ and $\Gamma \vdash \Psi$, we can combine these two proofs into one bigger proof by applying $\wedge$-Intro, netting us a proof of $\Gamma \vdash \Phi \wedge \Psi$.</li>
</ul>
<p><strong>Cases (iii), (iv), and (v)</strong> are all similar: look at the given proof we assume, and extend it via natural deduction to get the conclusion we want. $ \ \blacksquare$</p>
<h3 id="maximally-consistent-sets">Maximally Consistent Sets</h3>
<p>The central idea that we&#39;ll use to prove the completeness of $\mathcal{L}_1$ is <strong>maximally consistent sets</strong>.</p>
<p><strong>Definition (Maximally Consistent Sets):</strong> A set $\Gamma$ is <em>maximally consistent</em> (or maximally D-consistent with respect to a proof system $D$) when $\Gamma$ is ND-consistent, and if $\Gamma \cup \{\Phi \}$ is ND-consistent, then $\Phi \in \Gamma$.</p>
<p>We can think of maximally consistent sets as model universes, completely filled with as many rules (sentences) that determine the laws and facts of this universe without contradicting itself. One more sentence and $\Gamma$ would no longer be consistent.</p>
<p>Conveniently enough, maximally consistent sets hold the two properties we just discussed.</p>
<hr>
<p><strong><span id = "maximal-complete">Maximally Consistent Sets Are Complete:</span></strong> If $\Gamma \subseteq \textrm{Sen}(\mathcal{L}_1)$ is maximally consistent, then it is ND-consistent and ND-complete.</p>
<p><strong>Proof:</strong> By definition of maximal consistency, $\Gamma$ is ND-consistent.</p>
<p>Now suppose for a contradiction that $\Gamma$ was ND-incomplete, i.e. there&#39;s a sentence $\Phi$ such that $\Gamma \nvdash \Phi$ and $\Gamma \nvdash \neg \Phi$. Hence, I claim both $\Phi \in \Gamma$ and $\neg \Phi \in \Gamma$, making $\Gamma$ inconsistent and showing our assumption of its incompleteness incorrect. To show a sentence $\Psi \in \Gamma$, we can leverage the definition of maximal consistency that $\Gamma \cup \{\Psi \}$ is consistent. </p>
<ul>
<li>Consider for contradiction that $\Gamma \cup \{\neg \Phi \}$ is inconsistent. Then, it would prove everything, and in particular, it would also prove $\Gamma \cup \{\neg \Phi \} \vdash \Phi$. By $\neg$-Elim, we can see that also $\Gamma \vdash \Phi$ since $\neg \Phi$ can be discarded in that proof. But we already know that $\Gamma \nvdash \Phi$, so it must be that $\Gamma \cup \{\neg \Phi \}$ is consistent. By maximal consistency then, $\neg \Phi \in \Gamma$. </li>
<li>Same argument as before, but with assuming $\Gamma \cup \{\Phi \}$ is inconsistent. Similarly we can conclude $\Phi \in \Gamma$.</li>
</ul>
<p>Since $\{\Phi, \neg \Phi\} \subseteq \Gamma$, we have $\Gamma \vdash \Phi$ and $\Gamma \vdash \neg \Phi$ trivially, and thus with $\neg$-Elim, $\Gamma$ proves everything. Hence it is inconsistent, which contradicts that it is maximally consistent. Hence $\Gamma$ must be ND-complete. $ \ \blacksquare$</p>
<hr>
<p>Another nice property of maximally consistent sets is that they provability and membership are equivalent in $\Gamma$.</p>
<hr>
<p><strong>Membership Lemma:</strong> If $\Gamma$ is maximally consistent, then $\Gamma \vdash \Phi$ iff $\Phi \in \Gamma$. </p>
<p><strong>Proof:</strong> </p>
<ul>
<li>$(\Leftarrow)$ Clearly if $\Phi \in \Gamma$, then $\Gamma \vdash \Phi$ trivially.</li>
<li>$(\Rightarrow)$ Since $\Gamma \vdash \Phi$, by the consistency of $\Gamma$, we also have $\Gamma \nvdash \neg \Phi$ (since if it proved both, then we would be able to prove any sentence with $\neg$-Elim). We want to show $\Phi \in \Gamma$, which would be true if $\Gamma \cup \{\Phi\}$ was consistent (by definition of a maximally consistent set). Say for a contradiction that $\Gamma \cup \{\Phi\}$ was inconsistent, that is, it proves everything. If it proves everything, in particular, it also proves $\Gamma \cup \{\Phi\} \vdash \neg \Phi$. But then also, $\Gamma \vdash \neg \Phi$, since by $\neg$-Intro, we can discard the premise $\Phi$ as an assumed premise that we do not actually need concretely. This contradicts the fact that $\Gamma \nvdash \neg \Phi$, so our assumption must be wrong. Therefore, $\Gamma \cup \{\Phi\}$ is consistent, and hence $\Phi \in \Gamma$ by definition of a maximally consistent set.</li>
</ul>
<center>
$\blacksquare$
</center>

<hr>
<p>With these two lemmas in mind, we can now generalize membership for $\Gamma$ even broader:</p>
<hr>
<p><strong><span id="general-member">Generalized Membership Lemma:</span></strong> Suppose $\Gamma \subseteq \textrm{Sen}(\mathcal{L}_1)$ is maximally consistent. Then for all sentences $\Phi,\Psi$:</p>
<ol type="i">
  <li>$\neg\Phi \in \Gamma$ iff $\Phi \notin \Gamma$ </li>
  <li>$\Phi \wedge \Psi \in \Gamma$ iff $\Phi \in \Gamma$ and $\Psi \in \Gamma$</li>
  <li>$\Phi \vee \Psi \in \Gamma$ iff $\Phi \in \Gamma$ or $\Psi \in \Gamma$ (or both)</li>
  <li>$\Phi \rightarrow \Psi \in \Gamma$ iff $\Phi \notin \Gamma$ or $\Psi \in \Gamma$ (or both)</li>
  <li>$\Phi \leftrightarrow \Psi \in \Gamma$ iff $\Phi \in \Gamma$ and $\Psi \in \Gamma$, or $\Phi \notin \Gamma$ and $\Psi \notin \Gamma$</li>
</ol>

<p><strong>Proof:</strong> We&#39;ve already done all the work in the previous lemmas. $\Gamma$ is maximally consistent, so it&#39;s ND-consistent and ND-complete. By the Consistency and Completeness Lemma, we have all those cases about provability true in $\Gamma$. By the Membership Lemma, we can replace all those proofs with clauses of membership. $ \ \blacksquare$</p>
<hr>
<p>Now compare each of these cases of the Generalized Membership Lemma to what <a href="#satisfaction-and-truth-in-mathcal-l-_2-">satisfaction looks in a structure</a>. The relations are identical! This is the key property of maximally consistent sets: membership in $\Gamma$ acts like truth in an $\mathcal{L}_1$-structure. Likewise, we are able to not only make a maximally consistent set $\Gamma$, but also create a structure specifically tailored to satisfy $\Gamma$.</p>
<h3 id="constructing-a-maximally-consistent-set">Constructing a Maximally Consistent Set</h3>
<p>Maximally consistent sets are filled with as many sentences as possible while remaining consistent. So, if we wanted to make a maximally consistent set, we could just look at every sentence and see if we can add it to our bucket while remaining consistent.</p>
<p><strong><span id = "complete1">Completeness Lemma 1:</span></strong> Suppose we have an ND-consistent set $\Gamma$. Then there is a maximally consistent set $\Gamma^{+}$ with $\Gamma \subseteq \Gamma^{+}$.</p>
<p><strong>Proof:</strong> The idea is that there are a countably infinite number of sentence letters in $\mathcal{L}_1$, and therefore a countably infinite number of sentences in $\mathcal{L}_1$ too (the Cartesian product of two countably infinite sets is countably infinite). So we just go through all the possible sentences, add them to $\Gamma$ if preserves consistency, and at the end we obtain not just a consistent, but maximally consistent set.</p>
<p>Let $\textrm{Sen}(\mathcal{L}_1) = \{\Phi_0, \Phi_1, \Phi_2, \cdots\}$, and let $\Gamma_0 = \Gamma$. We then define the recursion</p>
<center>

$$ \Gamma_{n+1} = \begin{cases} \Gamma_n \cup \{\Phi_n\} \ \textrm{if it is ND-consistent}  \\ \Gamma_n \ \textrm{otherwise} \end{cases} $$

</center>

<p>Then let $\Gamma^{+} = \bigcup_{n} \Gamma_n$. By construction, $\Gamma_n$ is consistent and $\Gamma_n \subseteq \Gamma^+$ for all $n$. Importantly, including $n=0$, so $\Gamma = \Gamma_0 \subseteq \Gamma^+$.</p>
<ul>
<li>First we show that $\Gamma^+$ is ND-consistent. Say it wasn&#39;t. Then $\Gamma^+$ proves every sentence, so $\Gamma^+ \vdash \varphi$ and $\Gamma^+ \vdash \neg \varphi$ for some sentence $\varphi$. Proofs must be finite (what would an infinite proof look like?), so we only need finite premises to prove these claims:
<center>
$\{\gamma_1, \gamma_2, \cdots, \gamma_m \} \vdash \varphi$ where $\{\gamma_1, \gamma_2, \cdots, \gamma_n \} \subseteq \Gamma^+$ </br>
$\{\delta_1, \delta_2, \cdots, \delta_n \} \vdash \neg\varphi$ where $\{\delta_1, \delta_2, \cdots, \delta_n \} \subseteq \Gamma^+$
</center>
Where $m$ and $n$ are some positive integers. Then, the finitely many sentences of $\{\gamma_1, \gamma_2, \cdots, \gamma_m \} \cup \{\delta_1, \delta_2, \cdots, \delta_n \}$ must have appeared somewhere in our listing of $\textrm{Sen}(\mathcal{L}_1)$ and thus must all have been added to $\Gamma_k$ for some $k$. But then $\Gamma_k$ would be inconsistent as $\Gamma_k \vdash \varphi$ and $\Gamma_k \vdash \neg\varphi$, which cannot happen by construction. So $\Gamma^{+}$ is ND-consistent.</li>
<li>Now we need to show $\Gamma^{+}$ is maximally consistent. Say $\Gamma^{+} \cup \{\varphi\}$ is consistent. $\varphi$ must have appeared in our enumeration of $\textrm{Sen}(\mathcal{L}_1)$ at some point, i.e. $\varphi = \Phi_k$ for some $k$. $\Gamma^{+} \cup \{\Phi_k\}$ is consistent, and $\Gamma_k \subseteq \Gamma^{+}$, so it follows that $\Gamma_k \cup \{\Phi_k\}$ is consistent (subsets of consistent sets are consistent). So by our recursive construction of $\Gamma_{k+1}$, we have $\varphi = \Phi_k \in \Gamma_{k+1} \subseteq \Gamma^{+}$, so $\varphi \in \Gamma^{+}$. Hence $\Gamma^{+}$ is maximally consistent.</li>
</ul>
<center>
$\blacksquare$
</center>

<hr>
<p>So now we have a way of making a maximally consistent set.</p>
<h3 id="satisfying-a-maximally-consistent-set">Satisfying a Maximally Consistent Set</h3>
<p>We showed earlier maximally consistent sets treat membership almost identically to how sentences are true in a structure. As such, it shouldn&#39;t be surprising that we can create a structure that exclusively revolves around a maximally consistent set.</p>
<p><strong><span id = "complete2">Completeness Lemma 2:</span></strong> If $\Gamma$ is a maximally consistent set, then there&#39;s an $\mathcal{L}_1$ structure $A_{\Gamma}$ such that $A_{\Gamma} \vDash \Phi$ iff $\Phi \in \Gamma$.</p>
<p><strong>Proof:</strong> We prove this by giving an explicit structure: for a sentence letter $\alpha$, let $A_{\Gamma} \vDash \alpha$ iff $\alpha \in \Gamma$. We now show with induction on the complexity of sentences, that for <em>all</em> sentences $\Phi$ we still have $A_{\Gamma} \vDash \Phi$ iff $\Phi \in \Gamma$.</p>
<p><strong>Base Case:</strong> We defined $A_{\Gamma}$ by satisfying sentence letters our condition for sentence letters, so the base case holds.</p>
<p><strong>Inductive Hypothesis:</strong> Say this holds up to complexity $n$, and $\Phi$ is of complexity $n+1$. As with so many proofs before, there are 5 cases to consider, one for each connective in $\mathcal{L}_1$. The key tool we&#39;ll use is the <a href="#general-member">Generalized Membership Lemma</a> for maximally consistent sets.</p>
<p>$\underline{\Phi = \neg \Psi}:$ $\Gamma$ is maximally consistent by assumption, so $\Phi = \neg \Psi \in \Gamma$ iff $\Psi \notin \Gamma$. By the inductive hypothesis, $A_{\Gamma} \vDash \Psi$ iff $\Psi \in \Gamma$, so we deduce $A_{\Gamma} \nvDash \Psi$. Thus, by the semantic rule for $\neg$, we get $A_{\Gamma} \vDash \neg\Psi = \Phi$.</p>
<p>$\underline{\Phi = \Psi_1 \wedge \Psi_2}:$ $\Phi = \Psi_1 \wedge \Psi_2 \in \Gamma$ iff $\Psi_1 \in \Gamma$ and $\Psi_2 \in \Gamma$. By the inductive hypothesis then, $A_{\Gamma} \vDash \Psi_1$ and $A_{\Gamma} \vDash \Psi_2$. By the truth rules for $\wedge$, $A_{\Gamma} \vDash \Psi_1 \wedge \Psi_2$, and so $A_{\Gamma} \vDash \Phi$.</p>
<p>The other connectives are more of the same of what we&#39;ve done before. Hence we can create a structure that exactly and only satisfies members of a maximally consistent set. </p>
<center>
$\blacksquare$
</center>

<h3 id="the-proof-of-completeness">The Proof of Completeness</h3>
<p>We&#39;ve proven a lot about maximally consistent sets, and how they share a lot of properties to structures, but we&#39;ve actually done pretty much all the work we need to fully prove the completeness of $\mathcal{L}_1$.</p>
<p><strong>Completeness Theorem:</strong> If $\Gamma \vDash \Phi$, then $\Gamma \vdash \Phi$.</p>
<p><strong>Proof:</strong> We&#39;ll prove the contrapositive: if $\Gamma \nvdash \Phi$, then $\Gamma \nvDash \Phi$. So suppose that $\Gamma \nvdash \Phi$. As <a href="#maximal-complete">we&#39;ve seen many times before</a>, if $\Gamma \nvdash \Phi$, then $\Gamma \cup \{\neg \Phi\}$ is consistent. By <a href="#complete1">Completeness Lemma 1</a>, we can make a maximally consistent set $\Gamma^{+}$ out of $\Gamma \cup \{\neg\Phi\}$ i.e. $\Gamma \cup \{\neg\Phi\} \subseteq \Gamma^{+}$. By <a href="#complete2">Completeness Lemma 2</a>, we can find a structure $A$ such that $A \vDash \varphi$ iff $\varphi \in \Gamma^{+}$. Since $\Gamma \cup \{\neg\Phi\} \subseteq \Gamma^{+}$, we have $A \vDash \Gamma$ and $A \vDash \neg\Phi$. By the semantic rule for $\neg$, we also have $A \nvDash \Phi$. Thus by the definition of entailment $\Gamma \nvDash \Phi$. </p>
<center>
$\blacksquare$
</center>

<p>It&#39;s a relatively short proof, but that&#39;s mostly because we shoved a lot of the proof into the Completeness Lemmas 1 and 2. Not to mention, I don&#39;t know about you, but it is definitely not obvious to me that maximally consistent sets would be the tool that paved the path forward to prove completeness, let alone even have the intuition that $\mathcal{L}_1$ <i>is</i> complete. To realize that satisfiability in a structure is like membership in a maximally consistent set is already impressive, but to then think to <em>actually</em> link the two for this proof is very slick.</p>
<p>As a final aside, we can now deem $\mathcal{L}_1$ as having special status:</p>
<p><strong>Adequacy Theorem:</strong> $\Gamma \vdash \Phi$ if and only if $\Gamma \vDash \Phi$.</p>
<h3 id="completeness-of-other-logics">Completeness of Other Logics</h3>
<p>As before, I won&#39;t go into full detail, but $\mathcal{L}_2$ and $\mathcal{L}_=$ are likewise both complete logics as well. To extend the proof of completeness, it is very similar to how we would extend it for soundness, needing to just account for the quanitifers $\forall$ and $\exists$.</p>
<ul>
<li>First we would need to extend the <a href="#general-member">Generalized Membership Lemma</a>:<ul>
<li>$\exists v \Phi \in \Gamma$ iff $\Phi[t/v] \in \Gamma$ for some constant $t$</li>
<li>$\forall v \Phi \in \Gamma$ iff $\Phi[t/v] \in \Gamma$ for all constants $t$ </li>
</ul>
</li>
<li>Next would be to show that <a href="#complete2">Completeness Lemma 2</a> still holds, that is, every maximally consistent set of $\mathcal{L}_2$ sentences is satisfiable</li>
<li>Then the proof for completeness remains the same as before with $\mathcal{L}_1$</li>
</ul>
<h1 id="part-4-what-s-next-">Part 4: What&#39;s Next?</h1>
<p>This is where my logic sequence ended this year. But of course that does not mean that this is where logic as a field stops, too.</p>
<h2 id="more-to-be-studied-">More To Be Studied!</h2>
<p>Even before considering other logics or flaws within our current one, there is still many, extremely important results to be studied within $\mathcal{L}_1$, $\mathcal{L}_2$, and $\mathcal{L}_=$. </p>
<h3 id="compactness">Compactness</h3>
<p>One particularly strong result that deserves its own post is the <strong>Compactness Theorem:</strong></p>
<p><strong>Compactness Theorem:</strong> If every finite subset of a set of sentences $\Gamma$ is satisfiable, then the whole set $\Gamma$ is satisfiable.</p>
<p>We&#39;ve considered finite sets of sentences a lot already (as that&#39;s what proofs required of us), and the Compactness Theorem trivially holds for them since if $\Gamma$ is finite, then $\Gamma \subseteq \Gamma$ is a finite subset of itself. But for infinite sets of sentences, it&#39;s not entirely clear when they are satisfiable or not, and Compactness gives us a more tractable way of evaluating satisfiability.</p>
<p>The contrapositive gives us the equivalent formulation:</p>
<p><strong>Compactness Theorem:</strong> If $\Gamma$ is unsatisfiable, then there is a finite subset $\Gamma^{\textrm{fin}} \subseteq \Gamma$ that is unsatisfiable.</p>
<p>And this is <em>guaranteed</em> to hold for infinite sets, while it isn&#39;t for finite! Consider the unsatisfiable set $\{P, \neg P\} \vDash$ with clearly having its subsets (except itself) satisfiable. This has the immediate consequence that <em>every</em> argument $\Gamma \vDash \Phi$ can be captured in a <em>finite argument</em>.</p>
<p><strong><span id = "alternatecompact">Alternate Form of Compactness</span>:</strong> If $\Gamma \vDash \Phi$, then $\Gamma^{\textrm{fin}} \vDash \Phi$.</p>
<p><strong>Proof:</strong> If $\Gamma$ is finite already, then the claim holds as it is. So consider $\Gamma$ to be infinite. Recall that <a href="#valid-inconsistency">$\Gamma \vDash \Phi$ iff $\Gamma \cup \{\neg \Phi\}$ is inconsistent</a>. Then by Compactness, there is a finite subset $\Gamma^{\textrm{fin}} \cup \{\neg\Phi \}$ that is inconsistent. $\neg\Phi$ must be in this set as $\Gamma$ is satisfiable by assumption of $\Gamma \vDash \Phi$, so $\Gamma^{\textrm{fin}}$ is always satisfiable (if $\Gamma$ is unsatisfiable, then it entails everything, and then by Compactness there&#39;s a finite susbet that&#39;s also unsatisfiable that entails everything). Since $\Gamma^{\textrm{fin}} \cup \{\neg\Phi \}$ is inconsistent, then $\Gamma^{\textrm{fin}} \vDash \Phi$. $ \ \blacksquare$</p>
<p>Finally, it&#39;s worth noting that Compactness quickly follows from <em>any</em> logic that is both sound and complete:</p>
<p><strong>Proof of Compactness:</strong></p>
<center>
$\begin{array}{cc|cc}
\Gamma \vDash \Phi &amp; &amp; &amp; \textrm{Assumption} \
\newline
\Gamma \vdash \Phi &amp; &amp; &amp; \textrm{Soundness} \
\newline
\Gamma^{\textrm{fin}} \vdash \Phi &amp; &amp; &amp; \textrm{Proofs are finite} \
\newline
\Gamma^{\textrm{fin}} \vDash \Phi &amp; &amp; &amp; \textrm{Completeness} \
\end{array}$
</center>

<p>There are more ways to prove and apply Compactness, but that&#39;s for another day.</p>
<h3 id="l-wenheim-skolem-theorem">Löwenheim-Skolem Theorem</h3>
<p><strong>Löwenheim-Skolem Theorem:</strong> If $\Gamma$ is a set of $\mathcal{L}_=$ sentences with an infinite structure with cardinality $\omega$, then </p>
<ul>
<li>(Upward) $\Gamma$ has a structure of every cardinality $\omega&#39; &gt; \omega$</li>
<li>(Downward) $\Gamma$ has a countable structure</li>
</ul>
<p>The proofs found can be found in <em>Elements of Deductive Logic</em> (which only hold in <a href="#higher-order-logics">first-order logic</a>!), but there&#39;s an interesting paradox that comes along with it:</p>
<p><strong>Skolem&#39;s Paradox:</strong> The Löwenheim-Skolem Theorem says that no first-order theory can limit what the size of the structures that satisfy it. Set theory is a first-order theory, so the theorem would say that there is a countable structure that satisfies set theory. But set theory entails that there are <em>uncountable sets</em> as well. How can a structure with only countably many elements satisfy something that is uncountable? </p>
<p>I&#39;ll leave you to think about that, but the resolution to this dilemma (also in <em>Eagle</em>) leads to what is now known as the <a href = "https://en.wikipedia.org/wiki/Absoluteness_(logic)"> non-absoluteness </a> of set theory; a set may be uncountable <em>relative</em> to one structure, but countable to another.</p>
<h3 id="lindstr-m-s-theorem">Lindström&#39;s Theorem</h3>
<p>We&#39;ve looked at different ways logic can be limited in some math-y ways, like with expressive adequacy. The previous two theorems above give some more implicit restrictions on what a first-order logic can do. Compactness says that $\mathcal{L}_=$ can&#39;t discern finite sets from &quot;pseudo-finite&quot; (infinite sets whose finite subsets are satisfiable), and Löwenheim-Skolem says that it can&#39;t differentiate cardinalities of a structure. However, <strong>Lindström&#39;s theorem</strong> tells us that given these two restrictions of satisfying Compactness and (specifically the downward) Löwenheim-Skolem theorem, first-order logic is actually <strong>the strongest logic</strong> with these restrictions. Different definitions can yield different results, but analyzing the relative strength of logics is an area to still explore. Lindström uses the idea of overlapping &quot;good structures&quot; between two logics to determine their relative strengths.</p>
<h2 id="natural-language-and-grice-s-maxims">Natural Language and Grice&#39;s Maxims</h2>
<p>Remember, we started building logic with the intention to formalize English and natural language arguments. But obviously our formalizations above can only go so far, and one of the first, early signs of the &quot;weirdness&quot; logic might bring with it is the case of expressing, &quot;If… then…&quot; If you might recall we had the following truth tables:</p>
<center>
$
\begin{array}{c|c|c}
P &amp; Q &amp; \textrm{If} \ P \ \textrm{then} \ Q \\ \hline
T &amp; T &amp; ?  \\
T &amp; F &amp; F  \\
F &amp; T &amp; ?  \\
F &amp; F &amp; ?  \\
\end{array}
\ \ \ \
\begin{array}{c|c|c}
P &amp; Q &amp; P \rightarrow Q \\ \hline
T &amp; T &amp; T  \\
T &amp; F &amp; F  \\
F &amp; T &amp; T  \\
F &amp; F &amp; T  \\
\end{array}
$
</center>

<p>To get rid of those question marks, we decided to use $\rightarrow$, since it was easier to assign the case of vacuous more than anything else. So the only real information $\rightarrow$ carries is when it evaluates to false, telling us when one fact definitely does not result in another fact. For this reason, we call $\rightarrow$ the <strong>material implication</strong> as it only really cares about the current state of the <strong>actual world</strong>: if something $\Phi$ is true in our world and another thing $\Psi$ is false, it cannot be the case that in our world $\Phi \rightarrow \Psi$. </p>
<p>But that&#39;s not really how we usually use &quot;If… then…&quot; When someone uses &quot;if&quot;, it does not necessarily mean that they know that fact is true, but they&#39;re <em>supposing</em> that it&#39;s true; &quot;if&quot; can denote a <strong>hypothetical</strong>. Compare the following conditionals:</p>
<ul>
<li>If Apple <em>merges</em> with Google, then Samsung <em>does</em> not have a monopoly on smartphones.</li>
<li>If Apple <em>merged</em> with Google, then Samsung <em>would</em> not have a monopoly on smartphones.</li>
</ul>
<p>The use of &quot;would&quot; in the second case indicates something that <em>hasn&#39;t actually happend</em>, but describes a perfectly understandable situation that we can still parse information from. In the first sentence, $\rightarrow$ would deem that a true sentence since our antecedent is false i.e. Apple and Google have not merged in the actual world. But in the second case, that sentence is false, since it is conceivable that even if Apple and Google merged in an alternate universe, <strong>it is possible</strong> that Samsung could still be the number one seller of smartphones.</p>
<p>The <strong>counterfactual implication</strong>, denoted by the fancy symbol $\square \!\! \rightarrow$, captures these hypothetical situations we use all the time that our material implication just fails to render accordingly.</p>
<h3 id="grice-s-maxims">Grice&#39;s Maxims</h3>
<p>Note what we introduced above with $\square \!\! \rightarrow$ had no concrete semantics attached to it; our idea of hypotheticals, and &quot;would&quot; only arose out of what we understand in natural language, instead of something problematic from within the logic (or even English) itself. As such, this doesn&#39;t really give us a new truth table or anything, and unfortunately for logic, there are quite a few of these tacit rules to English.</p>
<p>For example, if I say, &quot;Either I will pass my job interview, or the other candidate will get in,&quot; there&#39;s an additional piece of information that&#39;s communicated beyond just the two possibilities: I don&#39;t know which case will occur. And according to our semantic rules for $\vee$ that formalize &quot;…or…&quot;, I could entail a disjunction by knowing a disjunct. That is, if I know $\Phi$, I certainly also know $\Phi \vee \Psi$ according to the truth table for $\vee$; $\Phi \vDash \Phi \vee \Psi$. Strictly speaking then, saying &quot;I will pass my job interview&quot; just contains more information as not only does it entail that &quot;or&quot; sentence I said at the beginning, but also an additional sentence (itself).</p>
<p>So if someone was to use any statement involving &quot;…or…&quot;, we would expect them to be telling us exactly as much information as we need to get their message across, that being that they just don&#39;t know either side of the &quot;…or…&quot; statement since if they did, they would just say it.</p>
<p>Paul Grice (1975) formalized these <strong>cooperative principles of communication</strong> into what is now know as <strong>Grice&#39;s maxims</strong> that describe these underlying, hidden aspects of language that we always use, but never explicitly write out or explain (since they are just expected). In no particular order, they are:</p>
<ol>
<li>Quantity: contribute as much information as is required without excess or lack of details.</li>
<li>Quality: contribute only as much as one knows and has evidence to be truthful.</li>
<li>Relation: contribute to the subject matter at hand; only be relevant.</li>
<li>Manner: be direct, clear, and avoid obscurity and esoteric constructions and words.</li>
</ol>
<p>Notably the maxim of quantity is what poses a difficulty for our logical language, as seen with &quot;…or…&quot; and $\vee$. Incorporating these maxims, though, is a possible direction one could look to enhance or strengthen their logic&#39;s utility and applicability.</p>
<h2 id="extensions-of-logic">Extensions of Logic</h2>
<p>Our logic above has done pretty well for what it needs to do concerning truth, and has found its way into computer science and discrete math as well by its very nature. But there are some arguments that go beyond truth alone.</p>
<h3 id="higher-order-logics">Higher-Order Logics</h3>
<p>A natural—and actually well-practiced—addition to logic are higher-order types. What we&#39;ve been working with is known as <strong>first-order logic</strong>, as we can only quantify over objects. That is, $\forall$ and $\exists$ only ranges over possible, single objects that satisfy a formula. But, there are many things we can say beyond just objects. For example, in math we often able to make claims about <strong>sets</strong> of numbers. The least-upper-bound property of the real numbers states that every nonempty subset of the real numbers has a least upper bound (i.e. the supremum exists).</p>
<p>Or even simpler, for any property $P$ and any object $x$, it must be the case that $Px \vee \neg Px$.</p>
<p><strong>Second-order logic</strong> is the upgrade we need that allows us to start <strong>quantifying over sets of objects</strong>. In first-order logic, it was predicates that took on the semantic value of sets of objects, so naturally second-order quantification looks like quantifying over predicates. So for our above example, it would look like: $\forall P \forall x(Px \vee \neg Px)$ where $P$ is now a variable standing in place for a predicate.</p>
<p>Quantifying over predicates/properties/sets of objects allows us to say quite a bit more as you&#39;d expect. Earlier we mentioned the <a href="#a-quick-aside-on-identity">difference between numerical identity and qualitative identity</a>, but now we are able to formalize how they relate to each other: </p>
<p><strong>The Indiscernibility of Identicals:</strong> $\forall x \forall y (x = y \rightarrow \forall P(Px \leftrightarrow Py))$</p>
<ul>
<li>If two things are numerically identical, then they certainly have all the same properties</li>
</ul>
<p><strong>The Identity of Indiscernibles:</strong> $\forall x \forall y (\forall P(Px \leftrightarrow Py) \rightarrow x = y)$</p>
<ul>
<li>If two things have all the same properties, then they should be the same object</li>
</ul>
<p>These are known as <a href="https://plato.stanford.edu/entries/identity-indiscernible/">Leibniz&#39;s laws</a>, and as discussed, the first is usually uncontested, while the second is more controversial. Whatever the case may be, second-order logic has given us a way to more clearly pick apart these claims.</p>
<p>But why stop there? First-order logic allowed us to quantify over objects; second-order logic allowed us to quantify over sets of objects (predicates). <strong>third-order logic</strong> allows us to quantify over sets of sets of objects, and the pattern continues. Second-order logic in particular is the most widely &quot;used&quot; from mathematics to computer science, but it should not be held to be necessarily &quot;better&quot; than first-order logic: <strong>second-order logic is actually incomplete</strong>.</p>
<p>Higher-order logic has its pulls and drawbacks, but it is a natural step from what we&#39;ve looked at today, especially if you&#39;re interested in the foundations of mathematics and set theory.</p>
<h3 id="universal-logics">&quot;Universal&quot; Logics</h3>
<p>We already saw with the counterfactual conditional $\square \!\! \rightarrow$, there are already some obvious cases our logic lacks. Not to mention, the idea of <strong>possible</strong> and <strong>necessarily</strong> pops up all the time in philosophy and arguments, that it&#39;s a little disconcerting that we can&#39;t already formalize them.</p>
<p><strong>Modal logic</strong> extends our logic precisely in this way, with two new quantifiers: We express, &quot;It is possible the case that P,&quot; as $\square P$, and, &quot;It is necessarily the case that P,&quot; as $\lozenge P$. The semantics of $\square$ and $\lozenge$ take our ideas of a structure as a model of the universe a little too literally. We say $\square P$ is true if there is <strong>a possible world</strong> in which $P$ is true, and we say $\lozenge P$ is true if in <strong>all possible</strong> worlds $P$ is true. The notion of what a possible world is by nature just vague, but it is an interesting one to consider. Ignoring semantics, we can already deduce a lot with these operators:</p>
<ul>
<li>$\neg \lozenge \Phi \equiv \square \neg \Phi$<ul>
<li>If it is not necessary that $\Phi$ occurs, there is a possible world in which $\Phi$ does not occur (i.e. $\neg \Phi$ occurs)</li>
</ul>
</li>
<li>$\neg \square \Phi \equiv \lozenge \neg \Phi$<ul>
<li>If it is not possible that $\Phi$ can occur, then it is necessarily the case that $\Phi$ does not occur (i.e. $\neg \Phi$ occurs)</li>
</ul>
</li>
</ul>
<p>As might be expected by the way we discussed their semantics, $\square$ and $\lozenge$ act a lot like $\exists$ and $\forall$ respectively.</p>
<p>Other extensions include <strong>temporal logics</strong>, that allow us to formalize time-sensitivity as well. The statement, &quot;It is raining right now,&quot; might have a constant meaning, but whether it is true or not changes based on time, thus motivating the formalization of predicates like &quot;eventually&quot;, &quot;always&quot;, &quot;until&quot;, and others that delineate time.</p>
<p><strong>Free logics</strong> allow us to abandon the need to have constants to actually mean anything, or even have a non-empty domain. Just because we can talk about an imaginary, non-real thing, like a unicorn (i.e. has the body of a horse, has one horn, etc.), does not necessarily mean that a unicorn exists. Yet, if we allow unicorns into our domain of a structure to logically discuss them, it would appear that we would be claiming the existence of a mythical creature, which becomes quite useful when discussing metaphysics and any ontology or description of existence (in a way, free logic is all about specifying the conditions of existence.).</p>
<h3 id="multivalue-and-fuzzy-logics">Multivalue and Fuzzy Logics</h3>
<p>We have only ever considered two possible ways to evaluate a sentence: it is either true or false. But is that really the case? Sounds kind of insane to even try and conceive of something else a sentence could be, but consider the following sentence:</p>
<center>
<strong>This sentence is false.</strong>
</center>

<p>If it is true, then it declares itself false. If it is false, then it declaring that it is false is wrong, so it is true. The cycle continues forever and ever, without ever resolving itself to one of our prescribed truth values. </p>
<p>So some propose a solution that include a third, deviant truth value that allows us to ascribe some sentences as neither true nor false in a <strong>3-value logic</strong>. Or another unintuitive solution is to allow <strong>degress of truth</strong>, i.e. the above sentence might be considered .5 true. Giving truth values between 0 and 1 is the cornerstone of <strong>fuzzy logic</strong>, which is usually used to describe when there is inexact information. However, don&#39;t confuse this number of truth as that of probability; it&#39;s not that this sentence is true only half the time, but rather that it&#39;s considered only half true since it is <em>vague</em>. Probability usually is associated with <em>ignorance</em> (lack of information; i.e. &quot;the coin will land heads with probability .5&quot; is said since we don&#39;t have knowledge of the future) as opposed to a lack of clarity. This notion is similar to the idea of <strong>degrees of membership in fuzzy set theory</strong>.</p>
<h3 id="altering-the-axioms">Altering the Axioms</h3>
<p>The tautology $P \vee \neg P$ is quite a natural one. &quot;Either it is or it is not.&quot; What other option could there be? Even in math we use double negatives multiplying to a positive, so positive and negative numbers seems to be the only cases possible. The <strong>law of excluded middle</strong> just seems to be a fact of the universe, that falls perfectly in line with our proofs and semantics for the <strong>classical logic</strong> we&#39;ve been looking at.</p>
<p>But I&#39;ve alluded throughout the post that some people do not always accept this as a given. <strong>Intuitionistic</strong>, or <strong>constructive logic</strong>, rejects the law of excluded middle, and argues that $\neg \neg P \nvDash P$, which come as standard inference rules that we can derive. The name comes from the fact that this doctrine encourages literal demonstrations of proof: if you have a proof of $P \wedge Q$, you literally have a proof of both $P$ and $Q$; a proof of $P \vee Q$ means one has a proof of $P$, or has a proof of $Q$.</p>
<p>Even more (ironically) unintuitive, <a href="xperimex.com/blog/constructive-proofs">we lose the ability to use proof by contradiction</a>, as that relies on the ability to claim that if an assumption is wrong, its negation is true. So for classic proofs like the irrationality of $\sqrt{2}$, intuitionists would claim that all that&#39;s been proven is that $\sqrt{2}$ is <em>not rational</em>, not necessarily that it is irrational.</p>
<p>Picking and choosing what axioms, entailments, or laws one accepts of course changes what meaning and truth will look like to them, and can lead to some interesting, tenable persepctives that hold real weight and become the focus of entire areas of philosophy.</p>
<h1 id="conclusion">Conclusion</h1>
<p>This post does not replace the two textbooks outlined above. If anything, it is only a simple supplement that gives a high-level overview of all the major conceptst to newcomers of formal logic, and a quick review source for those who have already studied it. At the very least, it&#39;ll be a quick reference for me, and future posts, as logic really has forced me to reconsider what I thought to be &quot;staple truths&quot;, not just in math, but life in general. We&#39;ll definitely revisist logic in the future whether it be from a computer science perspective with decidability and algorithms, certain shortcuts in math, or just more theory in logic itself. The way logic has developed in such an abstract way lends itself to be applied anywhere, it&#39;s just a matter of thinking about how, as it almost certainly can be.</p>
<!-- Find better count leading zeroes method -->
]]></description>
         <link>http://xperimex.github.io/blog/intro-logic</link>
         <guid isPermaLink="true">http://xperimex.github.io/blog/intro-logic</guid>
         <dc:creator><![CDATA[Adi Mittal]]></dc:creator>
      </item>
      <item>
         <title><![CDATA[The Hidden Universes of the Compactness Theorem]]></title>
         <description><![CDATA[No introduction. Just cool. 

 <script src='https://cdnjs.cloudflare.com/ajax/libs/g9/1.0.16/g9.js'></script>
<script src="https://unpkg.com/mathjs/lib/browser/math.js"></script>

<p>Last post, <a href="http://xperimex.com/blog/intro-logic/">I summarized the basics of formal logic</a>, starting from a philosophical context before building up to more broad and involved results, coming closer to what just looks like math by the end of it. One of those results which was briefly thrown into the conclusion was the <strong>Compactness Theorem</strong>. You won&#39;t need to know a lot of logic to appreciate the power of this theorem, but it would help to either skim that last blog post or brush up on how to read mathematical logic and its symbols. If the following talk of abstract logic seems confusing, don&#39;t worry, skip ahead to the <a href="#applications-of-compactness">Applications of Compactness</a> to see why this theorem is so much more than just abstract logic.</p>
<hr>
<p>Here a quick review of some concepts from <strong>propositional logic</strong> (that is, predicate calculus without quantifiers and predicates) we&#39;ll be using and discussing:</p>
<ul>
<li><strong>Sentence:</strong> a string of logical characters, built from sentence letters $\{P, Q, R, \cdots \}$ that are either true or false, and connectives $\{\wedge, \vee, \neg, \rightarrow, \leftrightarrow\}$</li>
<li><strong>Structure:</strong> a &quot;model universe&quot;; a total function that assigns every sentence letter a truth value. Complex sentences are assigned truth values according to the rules of the connectives they use.</li>
<li><strong>Satisfiability:</strong> a set of sentences $\Gamma$ is satisfiable if and only if there is a structure that makes every sentence in $\Gamma$ true</li>
<li><strong>Finite Satisfiability:</strong> a set $\Gamma$ is finitely satisfiable if and only if every finite subset of $\Gamma$ is satisfiable</li>
<li><strong>Entailment:</strong> We say a set $\Gamma$ entails a sentence $\Phi$, written $\Gamma \vDash \Phi$, for whenever a structure satisfies $\Gamma$, then $\Phi$ is also true</li>
</ul>
<hr>
<p><strong>Compactness Theorem:</strong> If $\Gamma$ is finitely satisfiable, then the whole set $\Gamma$ is satisfiable.</p>
<p>Roughly speaking, this says that if you have a set of logical statements, you can claim your set logical statements $\Gamma$ are not contradictory if every finite subset of logical statements are not contradictory themselves (we call the property of being non-contradictory <em>satisfiability</em>). If $\Gamma$ is already a finite collection of sentences, then Compactness trivially holds since $\Gamma \subseteq \Gamma$ is a finite subset of itself. </p>
<p>This becomes interesting when $\Gamma$ is <em>infinite</em>, since then this gives us a sufficient method for deducing a set of logical sentences is satisfiable. This should sort of make sense since if you can find a &quot;problem set&quot; within $\Gamma$ that are not satisfiable, then of course you can say $\Gamma$ is not satisfiable since if you try to make every sentence in $\Gamma$ not contradict each other, you&#39;ll have to find a way around the problem child set. This is essentially the contrapositive of the above formulation:</p>
<p><strong>Compactness Theorem:</strong> If $\Gamma$ is unsatisfiable, then there exists a finite subset of $\Gamma$ that is unsatisfiable.</p>
<p>To see the strength of compactness, we can use this final formulation of compactness along with the definition of entailment to get one more that shows a compact logics are able to reduce arguments to only some number of &quot;key&quot; premises:</p>
<p><strong>Compactness Theorem:</strong> <a href="https://xperimex.com/blog/intro-logic/#alternatecompact">If $\Gamma \vDash \Phi$, then $\Gamma^{\textrm{fin}} \vDash \Phi$.</a></p>
<p>This follows from an equivalent statement of entailment: $\Gamma \vDash \Phi$ if and only if $\Gamma \cup \{\neg\Phi\}$ is inconsistent (i.e. contradictory/unsatisfiable).</p>
<p>Even if an argument appears to need infinite premises $\Gamma$, there&#39;s an equivalent formulation that only requires a finite subset $\Gamma^{\textrm{fin}} \subseteq \Gamma$ that is what really matters to our argument. This relation between finite satisfiability and actual satisfiability, in a sense, states that there are certain &quot;pseudo-finite&quot; sets of sentences; they may look infinite, but for what you can deduce from them, they are no better than being a finite set of sentences.</p>
<p>We&#39;ll first cover some examples on why I think this theorem needs to be more known, where it gets its name from, and finally a proof of the Compactness Theorem for propositional logic.</p>
<h1 id="applications-of-compactness">Applications of Compactness</h1>
<p>I&#39;ve been going on a bit about this random theorem in a very abstract way—as logic tends to do. So, hopefully some examples will show just how useful this idea is; it gives us a way to extend results <em>to infinity</em>, which is not something that is all that common in math. Take <em>proof by induction</em>, for example: that gives us a way of showing a result holds for an arbitrary natural number, even as it approaches infinity. But to say the result holds at infinity is usually meaningless, even though we describe infinity or approaching infinity as that of the concept of an arbitrarily large number or similar.</p>
<h2 id="graph-theory">Graph Theory</h2>
<p>Due to the nature of graphs being readily characterized by a set of vertices and edges, they are surprisingly easy to formalize them and their properties in logic, making results fall out much quicker than you might expect.</p>
<h3 id="graph-coloring">Graph Coloring</h3>
<p>Let&#39;s start with a concrete example: graph coloring. We say a graph $G$ of vertices $V$ and edges $E$ (we define a graph as the object $G=(V,E)$ to clearly define its vertices and edges) is $4$-colorable if every vertex can be assigned one of four colors (say, red, blue, green, and purple) where no two vertices of the same color are neighbors (that is, share an edge). We say a graph is $k$-colorable if we can assign every vertex one of $k$ colors with no two of the same color neighboring each other.</p>
<p><img src="/img/compactness/Four_Colour_Map_Example.png"></p>
<center style="color: #666;">
<p>We assign every region a vertex, and connect two vertices if the two regions they represent share a border. Despite looking as complicated as it does, the above map is still 4-colorable. Credit: Wikipedia</p>
</center>


<p><strong>Theorem:</strong> A graph is $k$-colorable if and only if all of its finite subgraphs are $k$-colorable.</p>
<p><strong>Proof:</strong> $(\Rightarrow)$ Clearly if the whole graph is $k$-colorable, then all of its finite subgraphs are $k$-colorable.</p>
<p>$(\Leftarrow)$ For the other direction, we can write some logical sentences that describe the behavior of our graph. For a (undirected) graph $G=(V,E)$ with</p>
<ul>
<li>$V = \{1,2,\cdots, m\}$ as a set of verteices (we&#39;ll just label with numbers for convenience),</li>
<li>$E \subseteq V \times V$ as set of edges (that is an irreflexive and symmetric relation),<ul>
<li>I.e. if the pair $(1,2) \in E$, we mean there is an edge connecting vertices 1 and 2</li>
</ul>
</li>
<li>$C = \{1,2,\cdots, k\}$ as a set of colors, </li>
</ul>
<p>we&#39;ll define a set of sentence letters $P_{v,c}$ to represent $\textrm{&quot;vertex} \ v \ \textrm{has color} \ c \textrm{&quot;}$. With these simple sentences, we can write more complex descriptions of our graphs.</p>
<ul>
<li><strong>Vertex $v$ has at least one color:</strong> $F_v := \bigvee_{c=1}^{k} P_{v,c}$<ul>
<li>Either vertex $v$ has color 1, or color 2, or…, or color $k$<!-- * **Vertex $v$ has at most one color:** $G_v := \bigwedge\_{1 \leq c\_1 < c\_2 \leq k} \neg(P\_{v,c\_1} \wedge P\_{v,c\_2})$ --></li>
</ul>
</li>
<li><strong>Vertex $v$ has at most one color:</strong> $G_v := \bigwedge_{c_1 = 1}^{k} \bigwedge_{c_2 = c_1 + 1}^{k} \neg(P_{v,c_1} \wedge P_{v,c_2})$<ul>
<li>For any two different colors $c_1$ and $c_2$, it is not the case that vertex $v$ has both colors</li>
</ul>
</li>
<li><strong>Vertices $u$ and $v$ don&#39;t have the same color:</strong> $H_{u,v} := \bigwedge_{c = 1}^{k} \neg(P_{u,c} \wedge P_{v,c})$</li>
</ul>
<p>Now let $\Gamma = \{F_v \ | \ v \in V\} \cup \{G_v \ | \ v \in V\} \cup \{H_{u,v} \ | \ (u,v) \in E\}$. Now it should be fairly clear that $\Gamma$ is satisfiable and not contradictory if and only if $G$ is $k$-colorable. </p>
<ul>
<li>The first two sets of sentences $\{F_v \ | \ v \in V\} \cup \{G_v \ | \ v \in V\}$ says that every vertex has at at least one color and at most one color, that is, every vertex has exactly one color.</li>
<li>The last set $\{H_{u,v} \ | \ (u,v) \in E\}$ says that no neighboring vertices share the same color. If $G$ is $k$-colorable, then by definition, no two adjacent vertices have the same color.</li>
</ul>
<p>So an easy structure $A$ to define that satisfies $\Gamma$ is $A(P_{v,c}) = T$; i.e. let $P_{v,c}$ be true if and only if vertex $v$ has color $c$ (exactly as it denotes).</p>
<p>By assumption, every finite subgraph of $G$ is $k$-colorable, so every finite subset of $\Gamma$ is satisfiable. By the Compactness Theorem, then $\Gamma$ must be satisfiable, and hence all of $G$ is $k$-colorable. </p>
<center>
$\blacksquare$
</center>

<p>We can then combine this with the famous Four Color Theorem:</p>
<p><strong>Four Color Theorem:</strong> Every <em>finite</em> graph is 4-colorable.</p>
<p>And by the above, we can extend this to the</p>
<p><strong>Infinite Four Color Theorem:</strong> Every <em>infinite</em> graph is 4-colorable.</p>
<p><strong>Proof:</strong> Let $G$ be an infinte graph. Every finite subgraph of $G$ is 4-colorable, so by the above theorem, $G$ itself must also be 4-colorable. $\ \blacksquare$</p>
<p>The above method of formalizing and encoding behavior and relationships in math—and graph theory especially—alongside the Compactness Theorem gives us a nice, relatively straightforward strategy to extending finite results to the infinite.</p>
<h3 id="k-nig-s-lemma">Kőnig&#39;s Lemma</h3>
<p>Here&#39;s another result from graph theory that has its own handful of applications.</p>
<p><strong>Kőnig&#39;s Lemma:</strong> Every locally-finite infinite tree contains an infinite branch.</p>
<p>Just to be clear, here are some definitions: </p>
<ul>
<li>A <strong>tree</strong> is a special type of (undirected) graph characterized by being <strong>connected</strong> (there&#39;s a path between any two vertices) and that it is <strong>acyclic</strong> (there is no path from a vertex to itself without passing through a vertex more than once)</li>
<li>A <strong>locally-finite</strong> graph is one where every vertex only has a finite number of edges/neighbors (known as the <strong>degree of the vertex</strong>)</li>
<li>An <strong>infinite graph</strong> is a graph with an infinite number of vertices</li>
</ul>
<p>So a tree can look something like</p>
<!-- using the same graphics library from the Steiner porism blog draw a tree -->
<p><div id="example_tree" style="flex: 2; position: relative;"></div></p>
<script src="/js/compactness/example_tree.js"></script>

<p>Doesn&#39;t that sort of look like a tree growing downward? Here are some useful terms to describe trees:</p>
<ul>
<li>The very top vertex is called the <strong>root</strong></li>
<li>A vertex is at <strong>level $n$</strong> if it takes $n$ edges to get to that vertex from the root. So the root can be defined by being the vertex at level 0.</li>
<li>A vertex $x$ is the <strong>parent</strong> of another vertex $y$ (the <strong>child</strong>) if they share an edge, and $x$ is a level lower than $y$</li>
<li>$x$ is the <strong>ancestor</strong> of $y$ if there is a path (i.e. a chain of parents) connecting $x$ and $y$, which we denote $x \preceq y$</li>
</ul>
<p>So Kőnig&#39;s Lemma says every infinite tree either has an infinite-degree vertex or an infinite path. This should seem somewhat obvious, but as with anything involving infinity, it needs to be dealt with carefully. Since we can imagine building a tree where we carefully terminate every path to be finite. Sure, there may be arbitrarily long paths, but to show that there is an endless path as opposed to it being a very long finite path is a careful distinction. Moreover, Kőnig&#39;s Lemma, has ties to the axiom of choice, which should never be treated carelessly.</p>
<p><strong>Proof of Kőnig&#39;s Lemma:</strong> As before, we&#39;ll do this with the Compactness Theorem. For a tree $T$, we&#39;ll define a series of sentence letters $P_{x}$ to denote &quot;we select vertex $x$ in our path&quot;. The idea will be that—as the sentence suggests—to find a structure that enumerates specific $P_{x}$ at each level to tell us what our vertices will be in our path. The more complex sentences we will use and satisfy are:</p>
<ul>
<li><strong>We use at least one vertex at level $n$:</strong> $F_n := \bigvee_{i=1}^k P_{n_i}$ where $\{n_1, \cdots, n_k \}$ is the set of vertices at level $n$<ul>
<li>At level $n$, it must be the case we select either $n_1$, or $n_2$, or…, or $n_k$.</li>
</ul>
</li>
<li><strong>We pick at most one vertex at level $n$:</strong> $G_n := \bigwedge_{i = 1}^{k} \bigwedge_{j = i + 1}^{k} \neg(P_{n_i} \wedge P_{n_j})$<ul>
<li>For two different vertices $n_i$ and $n_j$ on level $n$, we do not pick both of them in our path</li>
</ul>
</li>
<li><strong>If we pick a vertex at some level, then we have to pick its ancestors:</strong> $H_{xy} := (P_{y} \rightarrow P_{x})$ where $x \preceq y$<ul>
<li>Since every vertex (except the root) has one parent, there&#39;s only one path from the root to that vertex, so naturally a line of ancestors forms our path</li>
</ul>
</li>
</ul>
<p>Now let $\Gamma = \{F_n \ | \ n \in \mathbb{N} \} \cup \{G_n \ | \ n \in \mathbb{N} \} \cup \{H_{xy} \ | \ x \preceq y \ \forall x,y \in T\}$. Now say there is a structure $A$ that satisfies $\Gamma$. Then it should be clear that the sequence of vertices $B = \{x \in T \ | \ A(P_x) = T\}$ would form an infinite path through our tree $T$:</p>
<ul>
<li>The set $\{F_n \ | \ n \in \mathbb{N} \} \cup \{G_n \ | \ n \in \mathbb{N} \}$ specifies we use exactly one vertex at each level, so there&#39;s this natural descent we can follow in our tree</li>
<li>The last set $\{H_{xy} \ | \ x \preceq y \ \forall x,y \in T\}$ says that if we pick one vertex in our tree to form our path, we also pick its ancestors, so we know there is this path of edges that we can actually follow</li>
</ul>
<p>To show that there is such a structure, we&#39;ll use Compactness. Take any finite subset $\Gamma^\textrm{fin} \subseteq \Gamma$. Let $\{x_1, x_2, \cdots, x_k\}$ be the set of vertices that have a corresponding sentence letter $P_{x_i}$ occurs in some element of $\Gamma^\textrm{fin}$. Since $\Gamma^\textrm{fin}$ only talks about a finite number of sentence letters and thus a finite number of vertices, it is also talking about a finite tree of height $n = \max\{\textrm{Lev}(x_1), \cdots, \textrm{Lev}(x_k)\}$ where $\textrm{Lev}(x_i)$ gives the level of vertex $x_i$. So let&#39;s pick some vertex at level $n$, and call it $\alpha$. Now the structure</p>
<center>

$$ A(P_x) = \begin{cases} T \ \textrm{iff} \ x \preceq \alpha  \\ F  \ \textrm{otherwise} \end{cases} $$

</center>

<p>should satisfy $\Gamma^\textrm{fin}$. Since every vertex has exactly one ancestor per level (i.e. its parent, the parent of the parent, etc.), this structure only satisfies one vertex per level as we&#39;d want, and by construction, obviously ensures we select a chain of ancestors to have a path. Even if our subset of our tree is disconnected, this structure would still satisfy $\Gamma^\textrm{fin}$ as if a vertex $x$ has no ancestors, it would vacuously satisfy $H_{xy}$.</p>
<p>Since $\Gamma^\textrm{fin}$ was an arbitrary finite subset of $\Gamma$ and was satisfiable, by the Compactness Theorem, $\Gamma$ is satisfiable, and so for any locally-finite infinite tree, there is an infinite path through it.</p>
<center>

$\blacksquare$

</center>

<p>There are direct proofs, too, but Kőnig&#39;s Lemma itself can be seen as a weaker version of Compactness, so I think proving it both ways is informative.</p>
<h2 id="order-extension-principle">Order-Extension Principle</h2>
<p>As the previous two examples with graphs have shown, results with Compactness are all about extending results in some way. Here&#39;s another one that doesn&#39;t necessarily rely on infinity like our previous ones, but first we&#39;ll need some definitions.</p>
<p>A <strong>partial order</strong> on a set $X$ is a relation $\preceq$ satisfying:</p>
<ul>
<li><strong>Reflexivity:</strong> $\forall x \in X \ x \preceq x$</li>
<li><strong>Antisymmetry:</strong> $\forall x,y \in X \ (x \preceq y \wedge y \preceq x \Rightarrow x = y)$</li>
<li><strong>Transitivity:</strong> $\forall x,y \in X \ (x \preceq y \wedge y \preceq z \Rightarrow x \preceq z)$</li>
</ul>
<p>A <strong>total order</strong> is a partial order with the additional restriction of</p>
<ul>
<li><strong>Connectedness:</strong> $\forall x,y \in X \ (x \preceq y \vee y \preceq x)$</li>
</ul>
<p>So a total order is something in which <em>all</em> elements are able to be compared with one another, while in a partial order some may not be. So all total orders are partial orders, but not all partial orders are total orders. We denote an a <strong>partially ordered set</strong> as a pair of a set and a partial order defined on the set: $(X, \preceq)$.</p>
<p>An easy example of a total order is $\leq$ on the set of integers $\mathbb{Z}$: every pair of integers contains a greater element. An example of a partial order would be the relation &quot;divides&quot; on $\mathbb{Z}$: 2 does not divide 3, and 3 does not divide 2, so under the relation of divides, 2 and 3 would be incomparable.</p>
<p>It&#39;s worth mentioning that there are also <strong>strict partial/total orders</strong> that remove the reflexivity requirement (think the difference between $$&lt;$$ and $\leq$ on the integers).</p>
<p>Now there is a natural question of whether or not we can remedy partial orders; is there a way we can maintain the structure of a partial order, but find a way to &quot;fix&quot; the incomparable elements. It turns out, we can do just that.</p>
<p><strong>Order-Extension Principle:</strong> Any partial order may be extended to a total order.</p>
<p>For any partial order $\preceq$ on a set $X$, we can find a total order $\leq$ on $X$ such that $\forall x,y \in X \ (x \preceq y \Rightarrow x \leq y)$; we can preserve all the original relationships from the partial order, while adding all the missing relations to make a total order without contradicting the criteria above. This isn&#39;t completely obvious to me, specifically for the transitivity rule, since it is totally possible to imagine accidentally creating a chain that circles on itself, coming to the conclusion that $x \preceq y \preceq z \preceq \cdots \preceq x$, getting us that distinct elements should be equal to each other by antisymmetry.</p>
<p>Until now, we&#39;ve been using the Compactness Theorem for propositional logic. For the following proof, we will use the Compactness Theorem for <strong>first-order logic</strong>, as this will allow us to talk about binary relations—which partial and total orders are. A relation $R$ on a set $X$ is a subset of $X \times X$, so we say that $xRy$ (or $x \preceq y$ in our case) is true iff the ordered pair $\langle x, y \rangle \in R$. The theorem is the exact same statement, just applies to a broader logic.</p>
<p><strong>Proof:</strong> Let $X$ be a set, and $\preceq$ be a partial order on $X$. We then add the binary relation $\leq$ to represent our partial order, and $\forall x \in X$, we add a constant $c_x$ to denote it. The following set of sentences will make up our $\Gamma$ that we&#39;ll show satisfiable:</p>
<ol>
<li>$\leq$ is a partial order<ul>
<li>This just specifies the content of $\leq$ so that it behaves how we want it to</li>
</ul>
</li>
<li>Whenever $p \preceq q$, we add the sentence $c_p \leq c_q$ <ul>
<li>Similar to sentences of form 1), this keeps the structure between our original partially ordered set and our formalization</li>
</ul>
</li>
<li>For every pair $p, q \in X$, we add the sentence $c_p \leq c_q \vee c_q \leq c_p$<ul>
<li>This is how we&#39;ll extend our partial order to a total order by ensuring every pair of elements is compared</li>
</ul>
</li>
</ol>
<p>Now we&#39;ll show that $\Gamma$ is satisfiable. Take some finite subset $\Gamma^\textrm{fin} \subseteq \Gamma$. If $\Gamma^\textrm{fin}$ only contains sentences from rules (1) and (2), then we know $\Gamma^{\textrm{fin}}$ is satisfiable, since $\preceq$ on $X$—which $\leq$ is based on—is a non-contradictory object (I mean, it exists), so that gives us a valid guide to make our structure. So $\Gamma^\textrm{fin}$ is satisfiable in this case.</p>
<p>Otherwise, $\Gamma^\textrm{fin}$ has a finite number of sentences from rule (3). To satisfy these sentences, we will extend our partial order $\preceq$ to another one $\preceq^{*}$. We can construct $\preceq^{*}$ by induction:</p>
<ul>
<li>If there is only 1 sentence from rule (3) which isn&#39;t already satisfied by $\preceq$, then, say, $p$ and $q$ are incomparable. So let&#39;s just state that $p \leq q$, and add this to our relation. So we let 
<center>
$\preceq^{*} \, = \,\, \preceq \cup \, \{\langle p, q&#39; \rangle \ | \ q \preceq q&#39; \ \forall q&#39; \in X \} \cup \{\langle p&#39;, q \rangle \ | \ p \preceq p&#39; \ \forall p&#39; \in X \}$ 
</center>
We can&#39;t just add $\langle p, q \rangle$ alone to our relation $\leq$, since we need to ensure transitivity. That&#39;s why we add these sets of ordered pairs as opposed to just the incomparable pair.</li>
<li>Now we do this exact same extension as before for the finite amount of sentences from rule (3), and we&#39;re done (we have no issue with the Axiom of Choice since we only need to consider finite numbers of sentences).</li>
</ul>
<p>So $\preceq^{*}$ gives us the precise model to show that $\Gamma^{\textrm{fin}}$ is satisfiable in this case. So in all cases, $\Gamma^{\textrm{fin}}$ is satisfiable, and by Compactness, $\Gamma$ is satisfiable too. (Note this isn&#39;t our total order, since it only acts on finite subsets of $\Gamma$, where we want our total order to act on all of $\Gamma$; $\leq$ is our total order)</p>
<p>So there is a structure in which $\Gamma$ is satisfied, which specifies that there is such a binary relation $\leq$ that acts as like a total order on $X$. We can define this total order $\leq^{*}$ specifically by: $p \leq^{*} q \Leftrightarrow (X, \leq^{*}) \vDash c_p \leq c_q$ (we have to distinguish $\leq$ and $\leq^{*}$ because one acts on our set, and the other acts as a binary relation in our language). </p>
<center>
$\blacksquare$
</center>

<h2 id="logical-results">Logical Results</h2>
<p>I hope the above gives some more concrete examples of how the Compactness Theorem applies to useful mathematics, despite it being a purely logical result. That being said, it being from logic should make it no surprise there are a number of purely theoretic results that are just interesting to consider.</p>
<h3 id="weakness-of-infinity">Weakness of Infinity</h3>
<p>First-order logic can readily <a href="https://xperimex.com/blog/intro-logic/#numerical-claims">express the size of a model/structure</a> fairly easily with quantification. The simple sentence $\varphi_{\geq 1} = \exists x (x=x)$ is satisfied if and only if the structure it is implemented in contains at least 1 element. $\varphi_{\geq 2} = \exists x \exists y (\neg x = y)$ is satisfied iff the structure contains at least 2 distinct elements. In general, $\varphi_{\geq n} = \exists x_1 \exists x_2 \cdots \exists x_n (\bigwedge_{1 \leq i &lt; j \leq n} \neg x_i = x_j)$ expresses the size of a structure to be at least of size $n$ elements.</p>
<p>Similarly, we can come up with upper bounds on the size of a structure with $\forall$: $\varphi_{\leq n} = \forall x_1 \forall x_2 \cdots \forall x_{n+1}(\bigvee_{1\leq i &lt; j \leq n+1} x_i = x_j)$. </p>
<p>Combining these can then get us exact sizes of structures: $\varphi_{= n} = \varphi_{\leq n} \wedge \varphi_{\geq n}$.</p>
<p>However, note that these only allow us to express <em>specific</em> finite sizes of structures. As it turns out, it is <strong>impossible</strong> to express in general the finitude of a model.</p>
<hr>
<p><strong>Claim:</strong> There is no sentence $\Phi$ that can be satisfied in and only in finite models.</p>
<p><strong>Proof:</strong> Suppose for a contradiction there was such a $\Phi$. Now consider the following set of sentences:</p>
<center>

$\Delta_{\infty} = \{\varphi_{\geq 1}, \varphi_{\geq 2}, \varphi_{\geq 3}, \cdots\} = \{\varphi_{\geq n} \ | \ n \in \mathbb{N} \}$

</center>

<p>It should be clear that $\Delta_{\infty}$ is only satisfied in an infinite model, since if the model was finite, then there would be some minimum element $\varphi_i$ that would not be satisfied by expressing the finitude of a structure greater than the finite one in question. </p>
<p>Now take $\{\Phi \} \cup \Delta_{\infty}$. This set of sentences should now be <em>unsatisfiable</em>, since $\Phi$ is only satisfied in finite models by assumption, while $\Delta_{\infty}$ is only satisfied in infinite ones. By the Compactness Theorem, there is a finite subset $\Gamma^{\textrm{fin}} \subseteq \{\Phi \} \cup \Delta_{\infty}$ that is unsatisfiable. If $\Gamma^{\textrm{fin}} \subseteq \Delta_{\infty}$, then let $n$ denote the greatest $\varphi_n \in \Gamma^{\textrm{fin}}$. Any model of size equal to or greater than $n$ clearly then satisfies $\Gamma^{\textrm{fin}}$. But since $\Gamma^{\textrm{fin}}$ is unsatisfiable, it must be the case that $\Phi \in \Gamma^{\textrm{fin}}$ as otherwise it would be satisfiable for the reason just listed. </p>
<p>But then in any such structure of size greater than $n$ that satisfies the finite component of $\Delta_{\infty}$, $\Phi$ must be unsatisfied to keep $\Gamma^{\textrm{fin}}$ unsatisfied. But then we have found a finite structure in which $\Phi$ is not satisfied, contradicting our assumption. $\ \blacksquare$</p>
<hr>
<p>As it turns out, it is <strong>also impossible</strong> to express the <em>infinitude</em> of a structure. </p>
<hr>
<p><strong>Claim:</strong> There is no sentence $\Phi$ that cannot be satisfied in and only in infinite models.</p>
<p><strong>Proof:</strong> Suppose for contradiction there was such a $\Phi$. Then for all finite structures $A$, it is the case that $A \nvDash \Phi$. Thus also in all such structures, $A \vDash \neg \Phi$. Now take the set of sentences $\Gamma = \{\neg \Phi\} \cup \Delta_{\infty}$ (same $\Delta_{\infty}$ as before). Any finite subset of $\Gamma$ is satisfiable, since any finite subset of $\Delta_{\infty}$ is satisfiable for some finite structure, and $\neg \Phi$ is satisfiable in all finite structures. By the Compactness Theorem, $\Gamma$ is satisfiable, so there is some structure $A^+$ such that $A^+ \vDash \Gamma$ i.e. $A^+ \vDash \neg \Phi$ and $A^+ \vDash \Delta_{\infty}$. Since $A^+ \vDash \Delta_{\infty}$, we must have $A^+$ be an infinite structure. But by assumption, $A^+ \vDash \neg \Phi$ if and only if it is finite. Thus there cannot be any such sentence $\Phi$ that is satisfied in and only in infinite structures. $\ \blacksquare$</p>
<hr>
<p>Just as propositional logic had the weakness of being able to not use quantifiers, we remedy it in strengthened first-order logic. In this way, this inability to express certain statements like the above might be seen as a flaw in first-order logic that needs some fix as well.</p>
<h3 id="extending-arithmetic-and-the-hyperreals">Extending Arithmetic and the Hyperreals</h3>
<p>The above proofs on the in-expressability of infinity are not all that interesting on their own, but they highlight a proof strategy using that specific set of $\Delta_{\infty}$ to force certain properties to arise out of satisfying $\Gamma$; by its simple construction, $\Delta_{\infty}$ does not usually affect finite satisfiability and hence satisfiability by Compactness, but forces our set $\Gamma$ to behave in a certain way. Here are some weirder consequence these types of proofs can result in.</p>
<p>We all know the <strong>standard model of arithmetic</strong>: that&#39;s just the natural numbers $\mathbb{N}$ with our normal understanding of addition, multiplication, etc. No more than the basic math we learned in elementary school. More formally, this is the standard model of the <a href="https://en.wikipedia.org/wiki/Peano_axioms">Peano axioms</a>, as $\mathbb{N}$ satisfies the axioms in the most &quot;obvious&quot; way that we are most familiar with.</p>
<p>But there are also <strong>non-standard models</strong> containing other numbers that are less commonly seen.</p>
<p><strong>Claim:</strong> There is a non-standard model of arithmetic.</p>
<p><strong>Proof:</strong> Let $P$ denote the Peano axioms. Now consider the set of sentences</p>
<center>

$\Gamma = P \cup \{x &gt; 0, x &gt; 1, \cdots\} = P \cup \{x &gt; n \ | \ n \in \mathbb{N}\}$

</center>

<p>for some new symbol $x$. If we can show $\Gamma$ is satisfiable, then we&#39;ll have shown that there is a model that not only satisfies the Peano axioms, but also includes a &quot;number&quot; $x$ that is greater than all other natural numbers.</p>
<p>If we take any finite subset $\Gamma^{\textrm{fin}} \subseteq \Gamma$, then it is satisfiable by the standard model of arithmetic (as those satisfy the Peano axioms), with the addition that $x$ is a number greater than any number mentioned in $\Gamma^{\textrm{fin}}$ (since it&#39;ll only have finitely many sentences of the form $x &gt; n$). By Compactness, since all finite subsets $\Gamma^{\textrm{fin}}$ are satisfiable, $\Gamma$ is satisfiable and has a model. </p>
<p>Since a model of $\Gamma$ is a model of $P$ (as it is just a susbet of $\Gamma$), it will be some model of arithmetic. But also, any model of $\Gamma$ that corresponds to $x$ cannot be any typical natural number, since $\Gamma$ states that it is greater than any natural number. So there is a non-standard model of arithmetic. $ \ \blacksquare$</p>
<p>In other words, there is a way to interpret our standard rules and axioms for finite numbers, and somehow apply them to infinite quantities. I don&#39;t know about you, but I was taught <em>never</em> to treat infinity like a number, but always as a concept or a process. Yet clearly it&#39;s not always contradictory or even bad logic to use them just like normal numbers.</p>
<p>Other non-standard models can have more complicated properties, like certain theorems failing that would be true in the standard model, but nonetheless it is interesting that Compactness implies that even such a model can exist and justifies our use of otherwise strange concepts.</p>
<p>For example, we can also show there is a <strong>non-standard model of analysis</strong>.</p>
<p><strong>Claim:</strong> There is a non-standard model of (real) analysis.</p>
<p><strong>Proof:</strong> Real analysis concerns itself with the ordered field of real numbers, so let&#39;s have $T$ be the set of sentences that all hold in this field. Now let&#39;s have </p>
<center>

$\Gamma = T \cup \{0 &lt; \epsilon &lt; 1, 0 &lt; \epsilon &lt; \frac{1}{2}, \cdots\} = T \cup \{0 &lt; \epsilon &lt; \frac{1}{n} \ | \ n \in \mathbb{N_{&gt;0}}\}$

</center>

<p>Like before, if we can show that $\Gamma$ is satisfiable, we&#39;ll find a model that satisfies all everything we would expect of the real numbers (from $T$) while also showing that we can introduce a new positive number $\epsilon$ that is smaller than any other number. Again like before, any finite subset $\Gamma^{\textrm{fin}}$ is satisfiable, since any finite subset of $T$ holds in the original model of the real numbers, and for any finite subset of $\{0 &lt; \epsilon &lt; \frac{1}{n} \ | \ n \in \mathbb{N_{&gt;0}}\}$, we just let $\epsilon$ be a number smaller than $\frac{1}{n}$ for the largest $n$ that appears in that set. Since any finite subset $\Gamma^{\textrm{fin}}$ is satisfiable and has a model, by Compactness, $\Gamma$ also is satisfiable and has a model. But clearly this model is non-standard for $\epsilon$ is a positive number that is not identical to any other positive real number, as it is smaller than all other positive reals. $\ \blacksquare \ $ (This also shows the existence of a <a href="https://en.wikipedia.org/wiki/Non-Archimedean_ordered_field">non-Archimedean ordered field</a>)</p>
<p>We are often reminded in math that we cannot treat the infinitely large and the infinitely small however we want, but there is a rigorous sense in which we <em>can</em> treat them familiarly as with all the other numbers. There is a sense in which you can do calculus and functional analysis without the need for limits, and just use these <strong>hyperreal</strong> or <strong>non-standard real numbers</strong>. If $h$ is one of these infintessimal hyperreal numbers (like $\epsilon$ from above), then we can define the derivative of a function $f$ at a point $x$ as</p>
<center>

$\large{f&#39;(x) = \textrm{st}(\frac{f(x + h) - f(x)}{h})}$ 

</center>

<p>This looks just like the standard definition of the derivative, but instead of having a limit attached to it, we have this new function $\textrm{st}(\cdot)$ that acts as a &quot;rounding function&quot;, of sorts, that turns our hyperreal fraction into a real number we can work with. If this interests you, here are some <a href="https://www.math.uci.edu/~isaac/NSA%20notes.pdf">nice notes on the topic</a>.</p>
<h1 id="topology-and-the-axiom-of-choice">Topology and the Axiom of Choice</h1>
<p>If it isn&#39;t clear by all the proofs we&#39;ve covered, the Compactness Theorem can lend its hand in many places of mathematics. To see just how powerful this is, we will need to explore its connections to other ideas we already briefly touched on. But, it&#39;s worth already pointing out, the name is a bit misleading, isn&#39;t it?</p>
<h2 id="topological-compactness">Topological Compactness</h2>
<p><strong>Compactness</strong>, as it stands as a property, is more often found in <strong>topology</strong> than anything, as a way of generalzing the notion of &quot;having no holes&quot;. For example, the set $(0,1)$ is not compact as it is missing its endpoints of 0 and 1. But, the closed interval $[0,1]$ is compact. The set of rational numbers $\mathbb{Q}$ is not compact as there are infinite holes in the <em>irrational numbers</em>: you can get as close as you want to any irrational number $r$ with a finite approximation in $\mathbb{Q}$, but clearly $r \notin \mathbb{Q}$, creating a &quot;hole&quot; of sorts.</p>
<p><strong>Definition 1:</strong> A subset $S$ of Euclidean space $\mathbb{R}^n$ is <strong>compact</strong> if $S$ is closed and bounded.</p>
<ul>
<li>Closed, meaning that $S$ contains all of its <em>limit points</em> (like the irrationals in the case of $\mathbb{Q}$: you can always get as close as you want to any irrational in $\mathbb{Q}$, but since they are not in $\mathbb{Q}$, it is not closed)</li>
<li>Bounded, meaning that every point in $S$ is a finite distance away from each other (so even $\mathbb{R} = (-\infty, \infty)$ is not compact as it is unbounded)</li>
</ul>
<p>In a way, compactness is the next best generalization of being <em>finite</em>; lots of the properties we&#39;d expect of finite sets generalize to compact ones, even though compact sets can be infinite like $[0,1]$. In fact, a finite set is just a discrete and compact set. For example, if a set $S$ is finite, then any continuous function $f: S \rightarrow \mathbb{R}$ is bounded. This trivially holds since if $S$ is finite, then $f(S)$ is also finite and we can just find its maximum and minimum to bound it. However, if $S$ is compact, this still remains true <a href="https://en.wikipedia.org/wiki/Extreme_value_theorem#Proof_of_the_boundedness_theorem">(Boundedness Theorem)</a>.</p>
<p>This should ring a bell, as this sort of sounds like the talk of pseudo-finite sets of sentences from the start: </p>
<p><strong>Compactness Theorem:</strong> <a href="https://xperimex.com/blog/intro-logic/#alternatecompact">If $\Gamma \vDash \Phi$, then $\Gamma^{\textrm{fin}} \vDash \Phi$.</a></p>
<p>If a logic is compact, all infinite sets of sentences mimic the behavior of finite subset of themselves. If a space is compact, then a set from that space acts a lot like a finite set. As it turns out, there is a definition that is much definition of topological compactness that even more closely resembles this idea:</p>
<p><strong>Definition 2:</strong> A set $S$ is <strong>compact</strong> if $S$ every <em>open cover</em> of $S$ has a finite subcover.</p>
<ul>
<li>An open cover is a collection of open sets $C$ such that $S = \bigcup_{X \in C} X$; an open cover is a collection of open sets in which every element of $S$ is in one of the open sets. For example, the collection of open intervals $\{(-n,n) \ | \ n \in \mathbb{N}\}$ is an open cover of $\mathbb{R}$.</li>
<li>According to the <a href="https://en.wikipedia.org/wiki/Heine%E2%80%93Borel_theorem">Heine-Borel theorem</a>, Definitions 1 and 2 are equivalent</li>
<li>We usually say <em>topologies/metric spaces</em> are compact, as opposed to generic sets</li>
<li>This definition applies to general topologies, not just Euclidean space $\mathbb{R}^n$</li>
</ul>
<p>But this isn&#39;t the &quot;real&quot; idea of the Compactness Theorem; in all of our proofs, the version of Compactness we really cared about was with finite satisfiability:</p>
<p><strong>Compactness Theorem:</strong> If $\Gamma$ is finitely satisfiable, then the whole set $\Gamma$ is satisfiable.</p>
<p>What we really liked was the ability to turn a problem of an infinite set into a more tractable, arbitrary finite one; we could take a <strong>local property and make it a global property</strong>. Topological compactness has a similar property:</p>
<p><strong>Finite Intersection Property:</strong> Given a collection of sets $X$ in a compact space, if every finite subset of $X$ has a non-empty intersection, then the whole set has a non-empty intersection.</p>
<ul>
<li>If we wanted to show a collection of sets shared a common element, the finite intersection property would give us a way to demonstrate that like the Compactness Theorem</li>
</ul>
<p>Referencing the Boundedness Theorem from above, we can think of it as if a function is locally bounded on a compact set, then it is also globally bounded.</p>
<p>There is, however, an even <em>tighter</em> <a href="https://iep.utm.edu/wp-content/media/CompactnessTheorem2.pdf">connection between topology and propositional logic</a>.</p>
<p><strong>Claim:</strong> The Compactness Theorem (of propositional logic) is equivalent to the claim that its associated valuation space is compact.</p>
<ul>
<li>A <em>valuation</em> is an assignment of True or False to every sentence letter (equivalent to a structure for propostional logic)</li>
</ul>
<p>Just as a reminder, here are the characteristics that determine a topology over a set $X$.</p>
<p><strong>Definition:</strong> A <strong>topological space</strong> $(X, \mathcal{T})$ consists of a non-empty set $X$ and a family $\mathcal{T}$ of subsets of $X$ with the following properties:</p>
<ul>
<li>$X, \emptyset \in \mathcal{T}$</li>
<li>$U,V \in \mathcal{T} \Rightarrow U \cap V \in \mathcal{T}$</li>
<li>If $U_i \in \mathcal{T}$ for $i = 1,2,\cdots$, then $\bigcup U_i \in T$</li>
</ul>
<p><strong>Proof:</strong> Let $V$ be the set of all valuations of our propositional logic. For every sentence $\phi$, we will assign it a set of valuations in which it&#39;s true: $U(\phi) = \{v \in V \ | \ v(\phi) = 1\}$. Now notice that for sentences $\phi_1$ and $\phi_2$,</p>
<ul>
<li>$V = \bigcup U(\phi)$ ranging over all sentences $\phi$<ul>
<li>This is easier seen by $V = U(P) \cup U(\neg P)$ for a sentence letter $P$</li>
<li>So the set $\{U(\phi) \ | \ \phi \textrm{ is a sentence}\}$ is a cover of $V$</li>
</ul>
</li>
<li>$U(\phi_1) \cap U(\phi_2) = \{v \in V \ | \ v(\phi_1) = 1\} \cap \{v \in V \ | \ v(\phi_2) = 1\} = U(\phi_1 \wedge \phi_2)$<ul>
<li>This is by definition of the truth table for $\wedge$</li>
<li>So $U(\cdot)$ is stable under intersection (we got another $U(\cdot)$ after intersection)</li>
</ul>
</li>
</ul>
<p>These two properties implies that $\{U(\phi) \ | \ \phi \textrm{ is a sentence}\}$ forms a <strong>basis of a topology</strong> over $V$.</p>
<ul>
<li>A basis of a topology $\mathcal{B}$ is a family of open sets such that for a topology $\mathcal{T}$, every set in $\mathcal{T}$ can be expressed as a union of sets from $\mathcal{B}$</li>
<li>The set $\{(a,b) \ | \ a,b \in \mathbb{R}\}$ is a basis for a (the standard) topology on $\mathbb{R}$</li>
</ul>
<p>So we are interested in the topological space $(V, \mathcal{T})$ where $\mathcal{T}$ is the topology generated by the basis $\{U(\phi) \ | \ \phi \textrm{ is a sentence}\}$.</p>
<p>Now lets consider some set of sentences $\Gamma$. $\Gamma$ is unsatisfiable if and only if for all valuations, at least one sentence in $\Gamma$ is false. Or equivalently, $\Gamma$ is unsatisfiable if and only if for all valuations, at least one sentence&#39;s negation $\neg \varphi$ is true. In terms of our $U(\cdot)$ function, we can also say $\Gamma$ is unsatisfiable if and only if each valuation is in one of the open sets (i.e. members of the topology) of the form $U(\neg \varphi)$ for $\varphi \in \Gamma$ (since $U(\neg\varphi)$ is precisely the set of valuations that make $\neg\varphi$ true). Equivalently, this also means that $\Gamma$ is unsatisfiable if $\{U(\neg\varphi) \ | \ \varphi \in \Gamma\}$ is an open cover of our topological space $V$ (recall what an open cover is from above if this isn&#39;t clear). So this shows the equivalence that </p>
<center>

$\Gamma \textrm{ is unsatisfiable} \Leftrightarrow \{U(\neg\varphi) \ | \ \varphi \in \Gamma\} \textrm{ is an open cover of } V$ 

</center>

<p>Now recall the Compactness Theorem: if $\Gamma$ is unsatisfiable, then there exists a finite subset $\Gamma^{\textrm{fin}}$ of $\Gamma$ that is unsatisfiable. So this gives us the equivalence:</p>
<center>

$\Gamma \textrm{ is unsatisfiable} \Leftrightarrow \exists \Gamma^{\textrm{fin}} \subseteq \Gamma \textrm{ that is unsatisfiable}$

</center>

<p>We can make this an if and only if since the Compactness Theorem gives us the $(\Rightarrow)$ direction, and the $(\Leftarrow)$ direction comes trivially by definition of unsatisfiability: if there is an unsatisfiable subset of $\Gamma$, then of course all of $\Gamma$ is unsatisfiable.</p>
<p>So, given the Compactness of propositional logic, we can combine these biconditionals to deduce that the Compactness Theorem is equivalent to the claim:</p>
<center>

If $\{U(\neg\varphi) \ | \ \varphi \in \Gamma\}$ is an open cover of the valuation space $V$, then there is a finite subset $\Gamma^{\textrm{fin}}$ of $\Gamma$ such that $\{U(\neg\varphi) \ | \ \varphi \in \Gamma^{\textrm{fin}}\}$ is an open cover of $V$.

</center>

<p>And that is precisely the definition of a compact space (see Definition 2 above).</p>
<center>
$\blacksquare$
</center>

<p>We were working with normal propositional logic above, but note that we didn&#39;t really assume anything about our logic in the proof. If we are working with an arbitrary logic with its own rules, symbols, connectives, etc., we could show that the Compactness Theorem holds if $V$ is compact. If you&#39;re interested in further reading the connection between logic and topology, <a href="https://en.wikipedia.org/wiki/Tychonoff%27s_theorem">Tychonoff&#39;s theorem</a> is actually the broader theorem that has the consequence of implying the Compactness Theorem (of propositional logic).</p>
<h2 id="the-axiom-of-choice">The Axiom of Choice</h2>
<p>The above shows, in my opinion, a fairly strong and fundamental use connection between logical compactness, to some more concrete math; it not only gives reason to its name, but also puts it into context of its broader origins.</p>
<p>There is an arguably EVEN MORE FUNDAMENTAL connection to math that the Compactness Theorem appeals to: the Axiom of Choice. We unwittingly saw this earlier when we proved König&#39;s Lemma, a weaker form of the Axiom of Choice.</p>
<p>To see this, it&#39;s worth considering a non-Compactenss proof of König&#39;s lemma. Here&#39;s a quick sketch:</p>
<p><strong>Alternative Sketch of König&#39;s Lemma:</strong> Let $v_0$ be the root of our finitely-branching tree $T$ with children $\{c_1, \cdots, c_k \}$. Now let&#39;s define $S_i = \{v \in T \ | \ c_i \textrm{ is the ancestor of } v \}$. These sets encapsulate possible vertices we can reach from a given child of $v_0$. Since each vertex has precisely one parent, it follows that $T \ \backslash \{v_0\} = S_1 \cup \cdots \cup S_k$ (we trivially take each vertex to be one of its own ancestors; you are related to yourself, no?). Since $T$ is an infinite tree, at least one of the $S_i$ has to be infinite, too (if they were all finite, then there would only be a finite number of vertices in our tree; think <a href="https://en.wikipedia.org/wiki/Pigeonhole_principle">Pigeonhole Principle</a>). So we pick a child $c_i$ with an infinite associated $S_i$, and let $v_1 = c_i$. Now we list the children of $v_1$ and simlarly construct there associated descendant sets $S_i$. At least one of the children of $v_1$ must have an infinite set of descendants, so we select that child and let it be $v_2$. We repeat this process over and over again, at each step, looking at the children of our previously selected vertex, and see which one has an infinite set of descendants, and let that be our next step in our infinite path $v_0, v_1, v_2, \cdots$ and so on. $\ \blacksquare$</p>
<p>There&#39;s a certain level of <em>choice</em> necessary here. At each step, we&#39;re picking a vertex with a certain property (infinite descendants), which is fine since we were able to show that there is at least one vertex at each step with that property. However, if there are <em>more</em> than one vertex, then which vertex do you choose? The need for the <strong>axiom of dependent choice</strong>, while weaker than the full axiom of choice, is nonetheless a choice principle that König&#39;s lemma depends on. In turn, you can also use <a href="https://tellerprimer.ucdavis.edu/pdf/2ch14.pdf/@@download/file/2ch14.pdf">König&#39;s lemma to prove Compactness</a>, giving the connection we want. </p>
<p>Spelled out a bit more, the idea is that the Compactness Theorem can be thought of as finding an infinite path in a tree of sentence letters and their negations: say $\Gamma = \{\Phi_1, \Phi_2, \cdots \}$ using sentence letters $\{P_1, P_2, \cdots\}$, and we let our tree be a <strong>binary tree</strong>, with each vertex containing exactly two children. We will let then find a path through the tree, where each step at level $n$, we can either take $P_n$ or $\neg P_n$ to be true (this can be seen as going on either the left or right branch of the tree). Any finite path of this tree defines a valuation, and in combination with the finite satisfiability of $\Gamma$ and König&#39;s lemma, you can find an infinite path that determines a structure that satisfies all of $\Gamma$.</p>
<p>But again, there&#39;s a level of <em>choice</em> necessary in picking a sentence letter or its negation. The Compactness Theorem can be seen as that specific choice principle. </p>
<p>Some other choice principles that Compactness is equivalent to the <a href="https://en.wikipedia.org/wiki/Ultrafilter_on_a_set">ultrafilter lemma</a>, and the Completeness Theorem, and some others, all of which are strictly weaker than the full axiom of choice. But again, this should not be that surprising given what we&#39;ve proven with Compactness, and the general nature of infinity itself. The <a href="#order-extension-principle">Order-Extension Principle</a> (which strongly resembles the ultrafilter lemma in form), while weaker than the axiom of choice, cannot be proven without it. I sort of even led you astray earlier, as Tychonoff&#39;s theorem from topology—that implies the Compactness Theorem—is actually just equivalent to the full axiom of choice.</p>
<p>Something so controversial and so important (literally makes up an entire letter in ZFC—Zermelo-Frankel set theory with the axiom of choice) is inextricably tied to the Compactness Theorem.</p>
<h1 id="proof-of-the-compactness-theorem">Proof of the Compactness Theorem</h1>
<p>This last section is to offer a proof of the Compactness Theorem for propositional logic to close. Since this will be a proof of a logical result, this section would definitely benefit from <a href="http://xperimex.com/blog/intro-logic/">knowing some basic logic</a>, just at the very least to more easily read notation. </p>
<p>Remember, propositional logic does not include the first-order quantifiers $\forall$ and $\exists$. To show Compactness holds in first-order logic (like we used in the Order-Extension Principle), we&#39;ll have to amend our proof.</p>
<p>We&#39;ll prove the following form of the Compactness Theorem:</p>
<p><strong>Compactness Theorem:</strong> If $\Gamma$ is finitely satisfiable, then the whole set $\Gamma$ is satisfiable.</p>
<p><strong>Proof of Compactess:</strong> The idea of the proof is we&#39;ll extend $\Gamma$ by squeezing in sentence letters in such a way that maintains finite satisfiability. By doing so, that will allow us to determine a structure that will satisfy $\Gamma$ by essentially finding what sentence letters we have to make true from our extended $\Gamma$, allowing us to carry out all the finite &quot;comparisons&quot; that force a structure to converge to one that will satisfy $\Gamma$. We&#39;ll break it down step-by-step.</p>
<p><strong>1) Definition of $\Gamma_i$:</strong> By our hypothesis, say that $\Gamma$ is finitely satisfiable. The set of sentence letters occurring in $\Gamma$ are enumerable, so let&#39;s do that with $P_1, P_2, \cdots$. Now let&#39;s define the following series of supersets. Let $\Gamma_0 = \Gamma$ and</p>
<center>

$$ \Gamma_{n+1} = \begin{cases} \Gamma_n \cup \{P_{n+1}\} \ \textrm{if it is finitely satisfiable}  \\ \Gamma_n \cup \{\neg P_{n+1}\} \ \textrm{otherwise} \end{cases} $$

</center>

<p><strong>2) Each $\Gamma_i$ is finitely satisfiable:</strong> We&#39;ll prove this by induction. $\Gamma_0 = \Gamma$ is finitely satisfiable by assumption. Now suppose $\Gamma_i$ is satisfiable for $i \leq n$. For the sake of contradiction, assume $\Gamma_{n+1}$ is not i.e. neither $\Gamma_n \cup \{P_{n+1}\}$ or $\Gamma_n \cup \{\neg P_{n+1}\}$ are finitely satisfiable. So there are finite subsets $\Delta$ and $\Sigma$ of $\Gamma_{n}$ such that $\Delta \cup \{P_{n+1}\}$ and $\Sigma \cup \{\neg P_{n+1}\}$ are unsatisfiable. Each of these sets must include $P_{n+1}$ and $\neg P_{n+1}$ since both $\Delta, \Sigma \subseteq \Gamma_{n+1}$ which is finitely satisfiable, so every finite subset of $\Gamma_{n}$ is satisfiable. </p>
<p>Further, clearly if $\Delta \cup \{P_{n+1}\}$ is unsatisfiable, clearly $\Delta \cup \Sigma \cup \{P_{n+1}\}$ is unsatisfiable (adding elements to a contradictory set won&#39;t make it less contradictory). Similarly, if $\Sigma \cup \{\neg P_{n+1}\}$ is unsatisfiable, then so is $\Delta \cup \Sigma \cup \{\neg P_{n+1}\}$. Since $\Delta \cup \Sigma \subseteq \Gamma_{n}$ is a finite subset from a finite satisfiable set, $\Delta \cup \Sigma$ is satisfiable. So in any structure/valuation in which $\Delta \cup \Sigma$ is true, it must be the case that either the sentence letter $P_{n+1}$ or its negation $\neg P_{n+1}$ is true. But we just said that both the sets $\Delta \cup \Sigma \cup \{P_{n+1}\}$ and $\Delta \cup \Sigma \cup \{\neg P_{n+1}\}$ are unsatisfiable. </p>
<p>This is a contradiction, so our initial assumption must be wrong, and $\Gamma_{n+1}$ must be finitely satisfiable.</p>
<p><strong>3) Defining a structure from the $\Gamma_i \textrm{s}:$</strong> For every sentence letter $P_i$, we will define a structure $A$ as follows:</p>
<center>

$$ A(P_i) = \begin{cases} T \ \textrm{if} \ P_i \in \Gamma_i  \\ F \ \textrm{otherwise; i.e.} \ \neg P_i \in \Gamma_i \end{cases} $$

</center>

<p>In step 2, we showed that for all $n$, $\Gamma_n$ is finitely satisfiable. Since</p>
<center>
$\Phi_n = \{P_i \in \Gamma_n \ | \ i \leq n\} \cup \{\neg P_i \in \Gamma_n \ | \ i \leq n\} \subseteq \Gamma_n$ 
</center>

<p>is a finite subset of $\Gamma_n$, the set $\Phi_n$ (just the set of sentence letters or their negations in $\Gamma_n$) is also satisfiable. By construction of our structure $A$, for every $n$, every sentence letter or its negation $\alpha \in \Phi_n$ is true in $A$. In particular, though, $\Phi_n$ is a finite subset, so we only need a finite amount of sentence letters to be assigned specific truth values to satisfy $\Phi_n$. So any structure which agrees (i.e. assigns the same truth value) to the members of $\Phi_n$ as $A$ does will also make satisfy $\Phi_n$ (this might seem obvious—if we give the same sentence letter values that satisfy $\Phi_n$ to those sentence letters, of course $\Phi_n$ will be satisfied—but this will be important in defining a full structure later).</p>
<p><strong>4) Showing $A$ satisfies $\Gamma$:</strong> Suppose for contradiction $A$ does not satisfy $\Gamma$. That is, for some sentence $\psi \in \Gamma$, $|\psi|_A = F$. By definition of a logical sentence, $\psi$ must be of finite length, and hence only have finitely many sentence letters occuring in it. Let $P_k$ be the highest numbered sentence letter (from our previous ordering in step 2) that occurs in $\psi$. As we discued in step 3, every $\alpha \in \Phi_k$ is true in a structure that agrees with $A$. Hence, $\psi$ must be false in every such structure too (since such a structure would fully determine the truth value of $\psi$ in the exact same way as $A$ did).</p>
<p>So we can conclude that $\Phi_k \cup \{\psi \}$ must be unsatisfiable. But $\Phi_k \cup \{\psi \} \subseteq \Gamma_k$ by construction of $\Gamma_k$. So by the finite satisfiability of $\Gamma_k$, it must be that $\Phi_k \cup \{\psi \}$ is also satisfiable. Contradiction. Therefore, our structure $A$ must satisfy $\Gamma$.</p>
<p>Since we found a structure that satisfies $\Gamma$, obviously it is satisfiable. So we&#39;ve shown that if $\Gamma$ is finitely satisfiable, then itself is satisfiable.</p>
<center>
$\blacksquare$
</center>

<h1 id="conclusion">Conclusion</h1>
<p>In a way, Compactness should sort of seem obvious. This idea of finite satisfiability basically allows us to make a bunch of finite comparisons of a property within a set, slowly but surely forcing the entire set to also conform to that property. In this case, it was satisfiability, but, say, if it was the property that every finite collection of numbers is prime, you&#39;d expect your whole set to also be prime. Yet, obviously this is still a theorem, and in fact is not always true for all logics. <a href="https://builds.openlogicproject.org/content/second-order-logic/metatheory/compactness.pdfhttps://builds.openlogicproject.org/content/second-order-logic/metatheory/compactness.pdf">Second-order logic does is not a compact logic</a>. But when it is true, it is an immensely powerful tool, allowing us to extend seemingly local properties to global ones. Compactness has made a name for itself in analysis and topology, but logic has given us a method to take that beyond simple set theory to graphs, computability, and all the way to the foundational axioms that make up modern math.</p>
]]></description>
         <link>http://xperimex.github.io/blog/compactness</link>
         <guid isPermaLink="true">http://xperimex.github.io/blog/compactness</guid>
         <dc:creator><![CDATA[Adi Mittal]]></dc:creator>
      </item>
      <item>
         <title><![CDATA[Your Induction to Induction]]></title>
         <description><![CDATA[Everything you need for discrete and continuous induction. 

 <script src='https://cdnjs.cloudflare.com/ajax/libs/g9/1.0.16/g9.js'></script>
<script src="https://unpkg.com/mathjs/lib/browser/math.js"></script>


<p>I&#39;ve been on a kick for mathematical foundations recently. Maybe it&#39;s all that <a href="http://xperimex.com/blog/compactness/">logic I&#39;ve been looking at</a>. One of those key ideas that finds its way into math is the <strong>Principle of Mathematical Induction</strong>. It&#39;s likely even if you&#39;ve only taken high school math classes, you&#39;ve encountered induction in one way or another. The importance of induction stems all the way back to the all-important, characterizing Peano axioms of arithmetic. In fact, any formal system that can perform induction is a critical indicator of not just the strength, but flaws of the system, as induction is the &quot;simplest&quot; cause of a logical system being incomplete (as in <a href="https://en.wikipedia.org/wiki/G%C3%B6del%27s_incompleteness_theorems">Gödel&#39;s incompleteness theorems</a>).</p>
<h1 id="principle-of-mathematical-induction">Principle of Mathematical Induction</h1>
<p>The usual idea of induction is proof by &quot;climbing a ladder&quot;, or &quot;knocking over mathematical dominoes&quot;. Let&#39;s have $\Phi(n)$ stand for &quot;the theorem $\Phi$ for the case of natural number $$n$$&quot;. Then if you can show that</p>
<ul>
<li>(PMI 1) $\Phi(0)$ is true</li>
<li>(PMI 2) $\forall k \geq 0$, if $\Phi(k)$ is true, then $\Phi(k+1)$ is true</li>
</ul>
<p>Then you can conclude that $\Phi(n)$ is true for all natural numbers $n \geq 0$. The idea is that in property (PMI 2), the theorem $\Phi$ is self-fulfilling; there is an inherent quality to our theorem $\Phi$ that has it proves many cases for itself. If we know $\Phi(0)$ is true, then by (PMI 2) we know $\Phi(1)$ is true. Similarly, from $\Phi(1)$ we then know $\Phi(2)$ is true, and then from $\Phi(2)$ we know $\Phi(3)$ and so on. We climb the mathematical ladder starting with a simple case $\Phi(0)$ we know for a fact is true.</p>
<p>This is best seen with an example. </p>
<hr>
<p>We will show the formula for the sum of the first $n$ integers is $\sum_{k=1}^n k = \frac{n(n+1)}{2}$.</p>
<p><strong>Base Case (PMI 1):</strong> The formula holds for $n=1$ since $\sum_{k=1}^1 k = 1 = \frac{1(1+1)}{2}$.</p>
<p><strong>Inductive Hypothesis (PMI 2):</strong> Let&#39;s assume our formula works for the first $n$ integers. We want to show that it holds for case $n+1$: $\sum_{k=1}^{n+1} k = \frac{(n+1)(n+2)}{2}$. We will show this by first rewriting our sum: $\sum_{k=1}^{n+1} k = \sum_{k=1}^{n} k + (n+1)$. By our assumption, we can reduce this to $\frac{n(n+1)}{2} + n+1$. Simplifying further, </p>
<center>
$
\begin{align}
\frac{n(n+1)}{2} + n+1 &amp; = \frac{n(n+1) + 2(n+1)}{2}
\newline
&amp; = \frac{(n+1)(n+2)}{2}
\end{align}
$
</center>

<p>Which is precisely the formula our hypothesis predicted. So by the PMI, for all $n$, $\sum_{k=1}^n k = \frac{n(n+1)}{2}$.</p>
<center>
$\blacksquare$
</center>

<hr>
<p>Here, we took a statement that can naturally be indexed by the natural numbers—in this case, a formula—and using the <strong>method</strong> of induction, proved our claim that the statement held. Note here that we didn&#39;t show $\Phi(0)$ is true, but rather $\Phi(1)$. This minor change isn&#39;t a big deal, since what we really want to show is a <strong>base case</strong> to build our inductive claim off of; we don&#39;t care where our ladder starts, so long as we can show there is <em>some</em> ground for it to stand on.</p>
<p>Induction is a very strong tool, as it does and can usually be applied to any claim that can be indexed by the integers; if there is a natural way to &quot;count&quot; the cases of your hypothesis, odds are induction could be useful.</p>
<p>However, note that induction didn&#39;t give us the arithmetic sum formula to begin with, but rather <strong>only a method to verify</strong> it. Some amount of intuition or case work needs to be done beforehand to get a hypothesis to follow through with induction.</p>
<p>Let&#39;s do a few more examples. Here&#39;s a simple one from set theory.</p>
<hr>
<p><strong>De Morgan&#39;s Laws:</strong> For sets $A_1, A_2, \cdots, A_n$, we have</p>
<center>
$(A_1 \cap A_2 \cap \cdots \cap A_n)^c = A_1^c \cup A_2^c \cup \cdots \cup A_n^c$
$(A_1 \cup A_2 \cup \cdots \cup A_n)^c = A_1^c \cap A_2^c \cap \cdots \cap A_n^c$
</center>

<p>Just as a reminder, for sets $A$ and $B$,</p>
<ul>
<li>$A \cup B = \{x \ | \ x \in A \textrm{ or } x \in B\}$ </li>
<li>$A \cap B = \{x \ | \ x \in A \textrm{ and } x \in B\}$ </li>
<li>$A^c = \{x \ | \ x \notin A\}$</li>
</ul>
<p>Notice how we&#39;re not working with integers directly, but rather integer amounts of sets. So, we&#39;ll then induct on the number of sets as our natural division of cases.</p>
<p><strong>Base Case:</strong> We&#39;ll show this for $n = 2$. Let $x \in (A \cap B)^c$ be an arbitrary element. Then $x \notin A \cap B$, so we have either $x \notin A$ or $x \notin B$ by the rules for $\cap$. Equivalently, $x \in A^c$ or $x \in B^c$, so regardless of which set $x$ is in, it must be the case that $x \in A^c \cup B^c$. Hence, since every element of $(A \cap B)^c$ is an element of $A^c \cup B^c$, so $(A \cap B)^c \subseteq A^c \cup B^c$. To summarize,</p>
<center>
$\begin{array}{ccc|cc}
&amp; x \in (A \cap B)^c &amp; &amp; &amp; \textrm{Assumption} \
\newline
&amp; x \notin A \cap B &amp; &amp; &amp; \textrm{Definition of set complement} \
\newline
&amp; x \notin A \textrm{ or } x \notin B &amp; &amp; &amp; \textrm{Rules for } \cap \
\newline
&amp; x \in A^c \textrm{ or } x \in B^c &amp; &amp; &amp; \textrm{Definition of set complement} \
\newline
&amp; x \in A^c \cup B^c &amp; &amp; &amp; \textrm{Rules for } \cup \
\newline \hline
\therefore &amp; (A \cap B)^c \subseteq A^c \cup B^c &amp; &amp; &amp; \textrm{Definition of subset}
\end{array}$
</center>

<p>Going the other way, suppose we have an arbitrary element $x \in A^c \cup B^c$. For the sake of contradiction, assume $x \notin (A \cap B)^c$. The rest of the proof is very similar to above.</p>
<center>
$\begin{array}{ccc|cc}
&amp; x \in A^c \cup B^c &amp; &amp; &amp; \textrm{Assumption} \
\newline
&amp; x \notin (A \cap B)^c &amp; &amp; &amp; \textrm{Assumption} \
\newline
&amp; x \in A \cap B &amp; &amp; &amp; \textrm{Definition of set complement} \
\newline
&amp; x \in A \textrm{ and } x \in B &amp; &amp; &amp; \textrm{Rules for } \cap \
\newline
&amp; x \notin A^c \textrm{ and } x \notin B^c &amp; &amp; &amp; \textrm{Definition of set complement} \
\newline
&amp; x \notin A^c \cup B^c &amp; &amp; &amp; \textrm{Rules for } \cup \
\newline
&amp; x \in (A \cap B)^c &amp; &amp; &amp; \textrm{Proof by contradiction} \
\newline \hline
\therefore &amp; A^c \cup B^c \subseteq (A \cap B)^c &amp; &amp; &amp; \textrm{Definition of subset}
\end{array}$
</center>

<p>The only way to sets can both be subsets of each other is if there equal to each other. So by <strong>double containment</strong>, $(A \cap B)^c = A^c \cup B^c$.</p>
<p><strong>Inductive Hypothesis:</strong> Let&#39;s assume our formula works for some number of $n$ sets. We want to show this works for $n+1$ sets. Fortunately most of our work was already done in the base case.</p>
<center>
$
\begin{align}
(A_1 \cap \cdots \cap A_n \cap A_{n+1})^c = ((A_1 \cap \cdots \cap A_n) \cap A_{n+1})^c &amp; = (A_1 \cap \cdots \cap A_n)^c \cup A_{n+1}^c \\
&amp; = A_1^c \cup \cdots \cup A_n^c \cup A_{n+1}^c
\end{align}
$
</center>

<p>Since $(A_1 \cap \cdots \cap A_n)$ is just another set, we can first use the case for 2 sets in the 2nd equality, and the case for $n$ sets in the last equality.</p>
<p>The proof for the second of De Morgan&#39;s Law is proved almost identically. </p>
<center>
$\blacksquare$
</center>

<hr>
<p>Let&#39;s pull another example from linear algebra.</p>
<hr>
<p><strong>Claim:</strong> Let $A$ be a square matrix. The eigenvectors of distinct eigenvalues of $A$ are linearly independent. </p>
<p>As a reminder:</p>
<ul>
<li>An <strong>eigenvector</strong> is a non-zero vector $\textbf{v}$ with corresponding <strong>eigenvalue</strong> $\lambda$ of matrix $A$ such that $A \textbf{v} = \lambda v$</li>
<li>We call  set of vectors $\{\textbf{v}_1, \cdots, \textbf{v}_k \}$ <strong>linearly independent</strong> when $a_1 \textbf{v}_1 + \cdots + a_k \textbf{v}_k = 0$ if and only if $a_1 = a_2 = \cdots = a_k = 0$ for scalars $a_1, \cdots, a_k$</li>
</ul>
<p>We&#39;ll induct on the number of eigenvectors.</p>
<p><strong>Base Case:</strong> For one eigenvector, it&#39;s clearly true, as $\textbf{v}_1 \neq 0$ by definition. So $a_1 \textbf{v}_1 = 0$ if and only if $a_1 = 0$.</p>
<p><strong>Inductive Hypothesis:</strong> Now suppose that the claim is true for fewer than $n$ eigenvectors of distinct eigenvalues. So suppose that</p>
<center>
$a_1 \textbf{v}_1 + a_2 \textbf{v}_2 + \cdots + a_n \textbf{v}_n = 0 \ \ \ \ (*)$
</center>

<p>We want to show $a_1 = a_2 = \cdots = a_n = 0$. Let&#39;s apply $A$ to both sides of $(*)$:</p>
<center>
$\begin{align}
A(a_1 \textbf{v}_1 + a_2 \textbf{v}_2 + \cdots + a_n \textbf{v}_n) &amp; = A(0) \\
a_1 \lambda_1 \textbf{v}_1 + a_2 \lambda_2 \textbf{v}_2 + \cdots + a_n \lambda_n \textbf{v}_n &amp; = 0 \ \ \ \ (1)
\end{align}$
</center>

<p>where each $\lambda_i$ are the associated eigenvalues. Now let&#39;s also multiply $(*)$ by $\lambda_1$:</p>
<center>
$a_1 \lambda_1 \textbf{v}_1 + a_2 \lambda_1 \textbf{v}_2 + \cdots + a_n \lambda_1 \textbf{v}_n = 0 \ \ \ \ (2)$
</center>

<p>Now let&#39;s subtract equation (2) from (1).</p>
<center>
$
\begin{array}{ccccccccc}
  &amp; a_1 \lambda_1 \textbf{v}_1 &amp; + &amp; a_2 \lambda_2 \textbf{v}_2 &amp; + &amp; \cdots &amp; + &amp; a_n \lambda_n \textbf{v}_n &amp; = 0 \\ 
- &amp; a_1 \lambda_1 \textbf{v}_1 &amp; + &amp; a_2 \lambda_1 \textbf{v}_2 &amp; + &amp; \cdots &amp; + &amp; a_n \lambda_1 \textbf{v}_n &amp; = 0 \\ \hline
  &amp; &amp; &amp; a_2(\lambda_2 - \lambda_1)\textbf{v}_2 &amp; + &amp; \cdots &amp; + &amp; a_n(\lambda_n - \lambda_1)\textbf{v}_n &amp; = 0 
\end{array}
$
</center>

<p>By the inductive hypothesis, we know the $n-1$ eigenvectors $\textbf{v}_2,\textbf{v}_3,\cdots,\textbf{v}_n$ are linearly independent, so all the coefficients $a_i(\lambda_i - \lambda_1) = 0$. But also remember, each $\lambda_i$ are distinct eigenvalues, so $\lambda_i - \lambda_1 \neq 0$ for $i=2,\cdots,n$. So the only way $a_i(\lambda_i - \lambda_1) = 0$ is if $a_i = 0$ for $i = 2,\cdots, n$. Plugging this back into $(*)$, we get that $a_1 \textbf{v}_1 = 0$, and since $\textbf{v}_1 \neq 0$, it must be that $a_1 = 0$. </p>
<p>Thus, all coefficients $a_1 = a_2 = \cdots = a_n = 0$, so the eigenvectors are linearly independent, having proven the inductive hypothesis.</p>
<center>
$\blacksquare$
</center>

<hr>
<p>Now induction doesn&#39;t always have to prove a positive claim. In fact, it can be combined with a proof by contradiction to prove a negative claim.</p>
<p><strong>Claim:</strong> $\cos(1^{\circ})$ is irrational.</p>
<p><strong>Proof:</strong> First, let&#39;s note the angle sum formula for cosine.</p>
<center>

$\cos(\alpha \pm \beta) = \cos(\alpha)\cos(\beta) \mp \sin(\alpha)\sin(\beta)$

</center>

<p>We can combine these to get the identity</p>
<center>

$\cos(\alpha + \beta) + \cos(\alpha - \beta) = 2\cos(\alpha)\cos(\beta)$

</center>

<p>Now let&#39;s assume for contradiction that $\cos(1^\circ)$ is rational. Now from our identity we just derived, let&#39;s note that</p>
<center>

$\cos(N + 1^\circ) + \cos(N - 1^\circ) = 2\cos(N)\cos(1^\circ)$

</center>

<p>Then, if we let $N = 1$, we can get an expression for $\cos(2^\circ)$.</p>
<center>

$\cos(2^\circ) = \cos(1^\circ + 1^\circ) = 2\cos(1^\circ)\cos(1^\circ) - \cos(1^\circ - 1^\circ) = 2\cos^2 (1^\circ) - 1$

</center>

<p>By our assumption that $\cos(1^\circ)$ is rational, $2\cos^2 (1^\circ) - 1$ is also rational, thus $\cos(2^\circ)$ is rational. Then using our identity </p>
<center>

$\cos(N + 1^\circ) = 2\cos(N)\cos(1^\circ) - \cos(N - 1^\circ)$

</center>

<p>We get $\cos(3^\circ)$ is rational by letting $N=2$. Then from that we get $\cos(4^\circ)$ is rational by letting $N=3$, and so on. Since we&#39;ve proven our base cases for $\cos(1^\circ)$ and $\cos(2^\circ)$ are rational, we get inductively that $\cos(n^\circ)$ is rational for all natural numbers $n$. </p>
<p>In particular, then according to our induction, $\cos(30^\circ)$ is rational. But $\cos(30^\circ) = \frac{\sqrt{3}}{2}$, which is irrational. Contradiction! Thus, our initial assumption that $\cos(1^\circ)$ is rational must have been wrong, or in other words, it must be that $\cos(1^\circ)$ is irrational.</p>
<center>
$\blacksquare$
</center>

<h2 id="choosing-a-base-case">Choosing a Base Case</h2>
<p>In our formulation of induction, we said in particular:</p>
<ul>
<li>(PMI 1) $\Phi(0)$ is true</li>
</ul>
<p>We specified our base case to be $n=0$. But if you look at our example proofs, we used $n=1$ and $n=2$ as base cases sometimes, such as in the proof of De Morgan&#39;s Laws. Usually the base case doesn&#39;t matter, as induction would just say that for a base case $k$, a claim holds for all $n \geq k$. But we have to be careful of our choice of base case. For example, here&#39;s a <em>false</em> inductive proof.</p>
<p><strong>Claim:</strong> All horses are the same color.</p>
<p><strong>Base Case:</strong> For $n=1$, obviously a horse is the same color as itself.</p>
<p><strong>Inductive Hypothesis:</strong> Suppose all sets of $n$ horses are the same color. Suppose we have $n+1$ horses, enumerated in some way (we assign each horse a number $1$ through $n+1$ to identify them). By the inductive hypothesis, the horses $1$ through $n$ are the same color. By the same inductive hypothesis again, horses $2$ through $n+1$ are the same color too. So all the horses are the same color as horses $2$ through $n$, thus showing that all $n+1$ horses are the same color. $\ \blacksquare$</p>
<p>Clearly this proof is wrong. Clearly some horses are brown, some are black, some are white, and some are patterned. Yet our &quot;proof&quot; would suggest otherwise. The issue lies in our base case, since it cannot be used to prove the case for $n=2$ horses. The key idea in the &quot;proof&quot; was to use the set of &quot;intermediary&quot; horses $2$ through $n$ to give some way of comparing horse $1$ with horse $n+1$ indirectly. But if there are only 2 horses, there is no middle horse to compare them to. If you want to prove that all horses are the same color in this way, you&#39;d have to show it initially for 2 horses to have any chance of a real argument (which of course, isn&#39;t true).</p>
<p>But as we saw in our proof that $\cos(1^\circ)$ is irrational, choosing a faulty base case can be useful. There, we purposely picked a bad base case (i.e. by assuming $\cos(1^\circ)$ is rational) to get to an observable contradiction to then prove a negative claim. The point still stands, though, you must be careful with how you choose and apply your base cases.</p>
<h2 id="1954237295746-">1954237295746 ≠ ∞</h2>
<p>Similar to the importance of choosing a base case, we must also be aware of what exactly induction is saying. The conclusion we get from an inductive argument is that $\Phi(n)$ is true for all natural numbers $n$. Note this doesn&#39;t mean it&#39;s true at a limit to $\infty$, it is only true for any arbitrarily large $n$. Consider the following faulty proof:</p>
<p><strong>Claim:</strong> $\pi$ is rational.</p>
<p><strong>Base Case:</strong> We&#39;ll induct on the number of decimal points in the expansion for $\pi$. For $n=0$, clearly $3$ is rational. </p>
<p><strong>Inductive Hypothesis:</strong> Say the truncation of $\pi$ to the $n$th decimal place, call it $x_n$ is rational. Then $\pi$ to the $(n+1)$st decimal can be written as $x_{n+1} = x_n + \frac{m}{10^{n+1}}$ for $m \in {0,1,\cdots,9}$. So $x_{n+1}$ is rational. So all decimal expansions of $\pi$ are rational, so $\pi$ is rational. $\ \blacksquare$</p>
<p>Clearly this is also wrong, and it&#39;s just by the misinterpretation we spelled out now: there is a difference between being true in the limit and true at each individual step to the limit.</p>
<h2 id="weak-induction-vs-strong-induction">Weak Induction vs. Strong Induction</h2>
<p>There&#39;s something else weird in our inductive proof of De Morgan&#39;s Laws. Again, let&#39;s look at our specific outline of induction:</p>
<ul>
<li>(PMI 2) $\forall k \geq 0$, if $\Phi(k)$ is true, then $\Phi(k+1)$ is true</li>
</ul>
<p>The inductive step says to show $\Phi(k)$ implies $\Phi(k+1)$. Yet, if you look at our proof of De Morgan&#39;s Laws, we had to use not only the case that $\Phi(k)$ was true, but also $\Phi(2)$ was true; we needed to assume that the law holds for not only $n$ sets, but for 2 sets as well. I mean, clearly if we assume that $\Phi(k)$ is true and $k \geq 2$, then $\Phi(2)$ should be true, but that&#39;s not what we explicitly allowed in our Principle of Mathematical Induction.</p>
<p>This is an instance of <strong>strong induction</strong>. The formulation of mathematical induction we gave before was <strong>weak induction</strong>, but the difference between them is minimal. If you can show that a theorem $\Phi$ holds for:</p>
<ul>
<li>(SPMI 1) $\Phi(0)$ is true</li>
<li>(SPMI 2) $\forall k \geq 0$, if $\Phi(0)\wedge\Phi(1)\wedge\cdots\wedge\Phi(k)$ is true, then $\Phi(k+1)$ is true</li>
</ul>
<p>then you can conclude that $\Phi(n)$ is true for all $n$. The difference between strong induction and weak induction is just that strong induction allows you to use multiple cases in your proof, while weak induction only specifies the previous case. </p>
<p>Here&#39;s a nice example of strong induction:</p>
<hr>
<p><strong>Claim:</strong> A country has $n$ cities. Suppose that any two cities are connected by a one-way road. Then there is a route that passes through every city.</p>
<p><strong>Base Case:</strong> Clearly it is true for $n=2$: just take the one-way road that leads out from one city and into the other.</p>
<p><strong>Inductive Hypothesis:</strong> Now suppose this holds up to and for $n$ cities. We want to show this holds for $n+1$ cities. Let&#39;s take the $(n+1)^{\textrm{th}}$ city, and divide the remaining cities into two groups: cities that have a road <em>into</em> city $n+1$ (call this group $A$) and cities that have roads <em>coming out of</em> city $n+1$ (group $B$). </p>
<p>Now obviously group $A$ has $n$ or fewer cities, so by the inductive hypothesis, there is a route that passes through all of the cities in group $A$. Similarly, for the same reason, there is a route that passes through all the cities in group $B$.</p>
<p>Now, take a route that passes through all the cities in $A$, then stop at the $(n+1)^{\textrm{th}}$ city, then finally go to a city in $B$ and complete a route that passes through all those cities. We can do that since every city in $A$ has a road to $n+1$, and every city in $B$ has a road from $n+1$. </p>
<p>Hence, the inductive hypothesis holds, and proves our claim. $\ \blacksquare$</p>
<hr>
<p>We needed strong induction above since we have no idea how many cities are in groups $A$ and $B$, so we need the claim to hold for <em>all</em> values up to $n$, not just $n$ itself, in the inductive hypothesis. The renewed inductive hypothesis given in strong induction is—obviously so—much more applicable than its weaker counterpart, just by sheer introduction of additional inductive instances. </p>
<!-- For example, recall that the Fibonacci numbers are defined by $F_{n+2} = F_{n+1} + F_n$ with $F_0 = 0$ and $F_1 = 1$. We can then prove that all Fibonacci numbers satisfy the explicit formula:

<center>

$\large{F_n = \frac{1}{\sqrt{5}} \left( \left(\frac{1+\sqrt{5}}{2} \right)^n - \left(\frac{1-\sqrt{5}}{2} \right)^n \right)}$

</center>

You could prove this with a modified induction principle: 

* Showing it holds for $n=0,1$, and then
* For all $k \geq 0$, if the formula holds for both $n$ and $n+1$, it will hold for $n+2$ -->
<p>Despite the naming, though, they are actually <strong>equal in strength</strong>; anything you can prove with weak induction you can prove with strong induction, and anything you can prove with strong induction you can prove with weak induction. </p>
<hr>
<p><strong>Strong Induction Implies Weak Induction:</strong> It shouldn&#39;t be much of a surprise that if strong induction holds, then weak induction also holds, since weak induction is just like strong induction but looser requirements. Let&#39;s prove it anyway. Suppose that strong induction is a valid proof technique. We want to show that weak induction is also valid. That is, from assumptions</p>
<ul>
<li>(WPMI 1) for some base case $k$ we know $\Phi(k)$ is true, and</li>
<li>(WPMI 2) $\forall m \geq k$, $\Phi(m)$ is true $\Rightarrow$ $\Phi(m+1)$ is true,</li>
</ul>
<p>we want to show that $\Phi(n)$ is true for all $n \geq k$. Obviously, whenever (WPMI 1) is true, then so is (SPMI 1) since they are both the same clause. However, let&#39;s also note that whenever (WPMI 2) is true, so is (SPMI 2). To see this, let&#39;s suppose (WPMI 1) is true. For any $m \geq k$, if $\Phi(k)\wedge\Phi(k+1)\wedge\cdots\wedge\Phi(m)$ is true, then certainly $\Phi(m)$ alone is true. By (WPMI 2), then we also know $\Phi(m+1)$, thus showing (SPMI 2) holds.</p>
<p>Having this fact in hand, we can complete the proof. Let&#39;s assume strong induction holds. Then, if the assumptions (WPMI 1) and (WPMI 2) for weak induction are true, we also know the assumptions (SPMI 1) and (SPMI 2) for strong induction are also true. Then by the conclusion for strong induction, we know $\Phi(n)$ holds for all $n$. But this is the exact same conclusion that we would get from weak induction. Hence weak induction holds whenever strong induction does. </p>
<center>
$\blacksquare$
</center>

<p>Again, this shouldn&#39;t be that surprising, as every instance of weak induction is just an instance of strong induction with weaker hypotheses.</p>
<p><strong>Weak Induction Implies Strong Induction:</strong> This direction will require a bit more work. Let&#39;s assume that weak induction is a valid proof technique. We want to show that strong induction is valid. That is, from the assumptions </p>
<ul>
<li>(SPMI 1) for some base case $k$ we know $\Phi(k)$ is true, and </li>
<li>(SPMI 2) $\forall m \geq k$, $\Phi(k)\wedge\Phi(k+1)\wedge\cdots\wedge\Phi(m)$ is true $\Rightarrow$ $\Phi(m+1)$ is true, </li>
</ul>
<p>we want to show that $\Phi(n)$ is true for all $n \geq k$. What we will do is <em>induct on a meta-statement</em> of $\Phi$. Let $S(m)$ be the statement &quot;$$\Phi(n)$$ is true for all $$k \leq n \leq m$$&quot;. If we can show $S(n)$ is true for all $n$ (with regular induction), then we would also show $\Phi(n)$ is true for all $n$ as well.</p>
<p>From (SPMI 1), we get $\Phi(k)$ is true, and thus $S(k)$ is also true (this will be our base case). From (SPMI 2), we get that for all $m \geq k$, if $S(m)$ is true, then $\Phi(m+1)$ is true (since $S(m)$ is equivalent to the hypothesis of the conditional). But, if $\Phi(m+1)$ is true and $S(m)$ is true, then we also get that $S(m+1)$ is true by definition. Combining these two conditionals, we get that if $S(m)$ is true, then $S(m+1)$ is true (this is our inductive step).</p>
<p>Combining our base case and inductive hypothesis for $S(n)$, we can deduce via weak induction, that $S(n)$ is true for all $n \geq k$. And as described before, it must be the case that $\Phi(n)$ is also true for all $n \geq k$, which is precisely the conclusion that strong induction wants.</p>
<p>Here&#39;s a more <a href="https://math.stackexchange.com/questions/1184541/what-exactly-is-the-difference-between-weak-and-strong-induction">intuitive version of this proof</a>, but relies on knowing some basic logic to justify a direct argument. The idea is the same, but the above is more &quot;contained&quot; in my opinion, while the link is more readily understandable.</p>
<center>
$\blacksquare$
</center>

<hr>
<p>So whenever, one proof looks like it requires strong induction, it could also be done with weak induction. For example, with De Morgan&#39;s Laws, you could imagine having shown the case for $n=2$, you could use weak induction to show $n=3$. Similarly, </p>
<p>So, perhaps a more appropriate name would just to say &quot;mathematical induction&quot;, for weak and strong induction are both cut from the same cloth.</p>
<h2 id="proving-induction">&quot;Proving&quot; Induction</h2>
<p>We showed that weak and strong induction are equivalent, meaning if one holds so does the other. But, we never showed that either form of <em>induction actually holds</em>. Intuitively, I think the analogy of dominos or climbing a ladder makes induction only seem natural, but with all things in math, we do need to justify using induction rigorously somehow. Fortunately, a lot of the work in the proof is given by the axioms that define the natural numbers. We&#39;ll first prove weak induction.</p>
<p><strong>Weak Induction:</strong> Let $S$ be a set of natural numbers with the following properties:</p>
<ol>
<li>$0 \in S$</li>
<li>If $k \in S$, then $k+1 \in S$</li>
</ol>
<p>Then $S$ is the set of all natural numbers.</p>
<p>Although this looks different to our above applications of induction, all we need to do is define our set such that $S = \{ n \in \mathbb{N} \ | \ \Phi(n) \textrm{ is true} \}$. Hopefully this is clear to be equivalent to our previous uses.</p>
<p><strong>Proof:</strong> We will <a href="https://xperimex.com/blog/constructive-proofs/">prove this by contradiction</a>. So suppose that there is some set of natural numbers $T \neq \varnothing$ that are not in $S$. By the <a href="https://en.wikipedia.org/wiki/Well-ordering_principle"><strong>well-ordering principle</strong></a>, $T$ has a smallest element—any two distinct natural numbers  has a lesser one among them two. Let&#39;s call this least element $\alpha$.</p>
<ul>
<li>Since $0 \in S$ by $(1)$, we have $0 &lt; \alpha \notin S$</li>
<li>By (the contrapositive) of $(2)$, we also have $\alpha - 1 \notin S$</li>
<li>Since $\alpha$ is the least element of $T$, we have $\alpha - 1 \notin T$, or in other words, $\alpha - 1 \in S$</li>
<li>This is a contradiction!</li>
</ul>
<p>So, our initial assumption that such a non-empty set $T$ exists must be false, and thus it must be that $S$ contains all natural numbers. $ \ \blacksquare$</p>
<p>Even though we&#39;ve proven the equivalence of weak and strong induction already, we can also prove the validity of strong strong induction independently in an almost identical fashion.</p>
<p><strong>Strong Induction:</strong> Let $S$ be a set of natural numbers with the following properties:</p>
<ol>
<li>$0 \in S$</li>
<li>If $0,1,\cdots,k \in S$, then $k+1 \in S$</li>
</ol>
<p>Then $S$ is the set of all natural numbers.</p>
<p><strong>Proof:</strong> We&#39;ll also prove this by contradiction. Suppose $T$ is the set of integers not in $S$, so $T$—by well-ordering—must have a least element $\alpha$.</p>
<ul>
<li>Since $0 \in S$ by $(1)$, we have $0 &lt; \alpha \notin S$.</li>
<li>By $(2)$, we have at least one element of $\{0,1,\cdots,\alpha -1\}$ that&#39;s not in $S$</li>
<li>But since $\alpha$ is the least element, $0,1,\cdots,\alpha -1 \notin T$ and so $0,1,\cdots,\alpha -1 \in S$</li>
<li>But then there is at least one element from $\{0,1,\cdots,\alpha -1\}$ that is both in and not in $S$</li>
<li>Contradiction!</li>
</ul>
<p>Since the only assumption we made was $T$ was non-empty, it must be wrong, and thus $S$ is the set of all natural numbers. $ \ \blacksquare$</p>
<h3 id="well-ordering-principle">Well-Ordering Principle</h3>
<p>In both proofs, we relied on the <strong>well-ordering of the natural numbers</strong>. A well-order is a relation $\leq$ on a set $X$ with the following properties:</p>
<ol>
<li><strong>Reflexivity:</strong> $\forall x \in X \ x \leq x$</li>
<li><strong>Antisymmetry:</strong> $\forall x,y \in X \ (x \leq y \wedge y \leq x \Rightarrow x = y)$</li>
<li><strong>Transitivity:</strong> $\forall x,y \in X \ (x \leq y \wedge y \leq z \Rightarrow x \leq z)$</li>
<li><strong>Connectedness:</strong> $\forall x,y \in X \ (x \leq y \vee y \leq x)$</li>
<li><strong>Minimums:</strong> Every non-empty subset $\varnothing \neq S \subseteq X$ contains a least element, i.e., $\exists \alpha \in S$ such that $\forall x \in S \ \alpha \leq x$</li>
</ol>
<p>The set of natural numbers $\mathbb{N}$ is well-ordered under the relation &quot;less than&quot; $\leq$. This is something that is just an intuitive fact that we take for granted when working with the natural numbers, but it is a very special property given by the axioms of the natural numbers, and it will become important to us later on. This simple fact, though, is actually <strong>equivalent to the principle of mathematical induction</strong> itself!</p>
<p><strong>Induction Implies Well-Ordering:</strong> Suppose for contradiction that $\mathbb{N}$ is not well-ordered. That is, there is a subset $\varnothing \neq S \subseteq \mathbb{N}$ with no least element. Then $0 \notin S$ as it would be then be minimal. Then $1 \notin S$ as $1$ would be minimal as $0 \notin S$. Suppose $0,1,\cdots,n \notin S$. Then $n+1 \notin S$ as it would be minimal. By induction, $\forall n \in \mathbb{N} \ n \notin S$. That is, $S = \varnothing$, which is a contradiction. Thus $\mathbb{N}$ is well-ordered. $ \ \blacksquare$</p>
<p><strong>Well-Ordering Implies Induction:</strong> Assume $\mathbb{N}$ is well-ordered. We want to show that if a subset $S\subseteq \mathbb{N}$ with the properties that</p>
<ol>
<li>$0 \in S$</li>
<li>If $k \in S$, then $k+1 \in S$</li>
</ol>
<p>then $S = \mathbb{N}$. </p>
<p>So for a contradiction, suppose $S \neq \mathbb{N}$. That is, there is a set of natural numbers $\varnothing \neq T \subseteq \mathbb{N}$ not in $S$. By well-ordering, $T$ has a least element $\alpha$. From assumption $(1)$, we&#39;re saying $0 \in S$, so $0 \notin T$. Therefore, $\alpha = k + 1$ for some $k \in \mathbb{N}$. But if $\alpha = k + 1 \in T$, $k + 1 \notin S$. And by assumption $(2)$, if $k + 1 \notin S$, then $k \notin S$ and further $k \in T$. But $k &lt; k+1 = \alpha$, contradicting the minimality of $\alpha$. </p>
<p>So if $T \neq \varnothing$, it contains no minimal element, contradicting the well-ordering of $\mathbb{N}$. Therefore, it must be that $T = \varnothing$, or in other words, $S = \mathbb{N}$, validating induction. $ \ \blacksquare$</p>
<hr>
<p>That&#39;s enough metatheory. Let&#39;s get back to some applications.</p>
<h1 id="variations-on-induction">Variations on Induction</h1>
<p>The simple idea of induction is far more flexible than our statement of it may seem. With some clever combinations of inductive arguments, we can prove many things in much simpler ways than typical induction may suggest.</p>
<h2 id="forward-backward-induction">Forward-Backward Induction</h2>
<p>Induction hopefully should clearly work in an &quot;forward&quot; direction at this point; we can climb the integer ladder up and up so long as we have one rung to start on. Similarly we can have a &quot;backward&quot; inductive (BI) argument: if you can show that for some claim $\Phi$ that</p>
<ul>
<li>(BI 1) For some base case $k$ we know $\Phi(k)$ is true</li>
<li>(BI 2) $\forall m \geq k$, $\Phi(m)$ is true $\Rightarrow$ $\Phi(m-1)$ is true</li>
</ul>
<p>then, naturally, we should be able to conclude that $\Phi(n)$ is true for all $n \leq k$. But we can use this idea in tandem with our normal form of induction to get a nice combined approach with <strong>forward-backward induction</strong>. If you can show that</p>
<ul>
<li>(F-B 1) $\Phi(n)$ is true for infinitely many $n$</li>
<li>(F-B 2) For all $k$, if $\Phi(k)$ is true, then $\Phi(k-1)$ is true</li>
</ul>
<p>then you can conclude that $\Phi(n)$ is true for all positive $n$. The idea is that you only need to show that $\Phi$ is true for an infinite amount of $n$, not necessarily <em>all</em> $n$. Then using (F-B 2), we can fill in the gaps between our infinite $\Phi(n)$ by working backwards from the proven cases in (F-B 1). Here&#39;s a more specific, but common example of forward-backward induction.</p>
<ul>
<li>For some base case $k$ we know $\Phi(k)$ is true</li>
<li>$\forall m \geq k$, $\Phi(m)$ is true $\Rightarrow$ $\Phi(2m)$ is true</li>
<li>$\forall m \geq k$, $\Phi(m)$ is true $\Rightarrow$ $\Phi(m-1)$ is true</li>
</ul>
<p>Here we show that all the powers of 2 (scaled by our base case) satisfy $\Phi(n)$, and then fill in all the gaps with our third condition that works backwards.</p>
<p>So really, forward-backward induction is just two inductive arguments being put together, which is more common than it may seem. For example, if you can show that </p>
<ul>
<li>$\Phi(0)$ and $\Phi(1)$ are true</li>
<li>For all $k \geq 0$, $\Phi(k)$ is true $\Rightarrow$ $\Phi(k+2)$ is true</li>
</ul>
<p>then $\Phi(n)$ is true for all $n$ as we just showed that $\Phi(n)$ is true for all even numbers and odd numbers separately; $\Phi(0)$ with the inductive step gets you the evens, while $\Phi(1)$ gets the odds. Forward-backward induction is the same idea, only combining two other inductive proofs to &quot;fill in the gaps&quot;.</p>
<p>Let&#39;s put it to practice.</p>
<hr>
<p><strong>Arithmetic Mean-Geometric Mean (AM-GM) Inequality:</strong> For non-negative real numbers $a_1,a_2,\cdots,a_n$,</p>
<center>

$\sqrt[n]{a_1 a_2 \cdots a_n} \leq \large{\frac{a_1 + a_2 + \cdots + a_n}{n}}$

</center>

<p>with equality given if and only if $a_1 = a_2 = \cdots = a_n$.</p>
<p><strong>Base Case:</strong> Clearly $n=1$ holds, so we&#39;ll also show it for $n=2$. Note that $\left(\sqrt{a_1} - \sqrt{a_2} \right)^2 \geq 0$. So by simple algebra,</p>
<center>
$
\begin{align}
\left(\sqrt{a_1} - \sqrt{a_2} \right)^2 &amp; \geq 0
\newline
a_1 - 2\sqrt{a_1 a_2} + a_2 &amp; \geq 0
\newline
a_1 + a_2 &amp; \geq 2\sqrt{a_1 a_2}
\newline
\frac{1}{2}(a_1 + a_2) &amp; \geq \sqrt{a_1 a_2}
\end{align}
$
</center>

<p><strong>Forward-Inductive Hypothesis:</strong> Let&#39;s assume the AM-GM inequality holds for some $n$. We&#39;ll show it also holds for $2n$.</p>
<center>
$
\begin{align}
\frac{a_1 + a_2 + \cdots + a_{2n}}{2n} &amp; = \frac{\frac{a_1 + a_2 + \cdots + a_{n}}{n} + \frac{a_{n+1} + a_{n+2} + \cdots + a_{2n}}{n}}{2}
\newline
 &amp; \geq \frac{\sqrt[k]{a_1 a_2 \cdots a_n} + \sqrt[k]{a_{n+1} a_{n+2} \cdots a_{2n}}}{2}
\newline
 &amp; \geq \sqrt{\sqrt[k]{a_1 a_2 \cdots a_n} \sqrt[k]{a_{n+1} a_{n+2} \cdots a_{2n}}}
\newline
 &amp; = \sqrt[2k]{a_1 a_2 \cdots a_n a_{n+1} a_{n+2} \cdots a_{2n}}
\end{align}
$
</center>

<p>Hence proving the forward inductive claim using cases for $2$ and $n$ non-negative numbers.</p>
<p><strong>Backward-Inductive Hypothesis:</strong> Again we suppose AM-GM inequality holds for $n$ numbers. We will show it holds for $n-1$ numbers. First, though, since AM-GM holds for $n$ numbers, it will also hold when we let $a_n = \frac{a_1 + \cdots + a_{n-1}}{n-1}$ the average of the previous $n-1$ numbers.</p>
<center>
$
\begin{align}
\frac{a_1 + a_2 + \cdots + a_{n}}{n} &amp; \geq \sqrt[n]{a_1 a_2 \cdots a_n}
\newline
\frac{a_1 + a_2 + \cdots + \frac{a_1 + a_2 + \cdots + a_{n-1}}{n-1}}{n} &amp; \geq \sqrt[n]{a_1 a_2 \cdots a_{n-1} \frac{a_1 + a_2 + \cdots + a_{n-1}}{n-1}}
\newline
\frac{a_1 + a_2 + \cdots + a_{n-1}}{n-1} &amp; \geq \sqrt[n]{a_1 a_2 \cdots a_{n-1} \frac{a_1 + a_2 + \cdots + a_{n-1}}{n-1}}
\newline
\left(\frac{a_1 + a_2 + \cdots + a_{n-1}}{n-1} \right)^n &amp; \geq a_1 a_2 \cdots a_{n-1} \frac{a_1 + a_2 + \cdots + a_{n-1}}{n-1}
\newline
\left(\frac{a_1 + a_2 + \cdots + a_{n-1}}{n-1} \right)^{n-1} &amp; \geq a_1 a_2 \cdots a_{n-1}
\newline
\frac{a_1 + a_2 + \cdots + a_{n-1}}{n-1} &amp; \geq \sqrt[n-1]{a_1 a_2 \cdots a_{n-1}}
\end{align}
$
</center>

<p>Thus proving the backward-inductive hypothesis.</p>
<p>By forward-backward induction, we&#39;ve shown that AM-GM holds any number of non-negative real numbers. </p>
<center>
$\blacksquare$
</center>

<h2 id="proof-by-infinite-descent">Proof by Infinite Descent</h2>
<p>Building on this idea of using backwards induction, Fermat used backward induction in a very neat way. Because, well, there&#39;s something weird going on in our forward-backward induction, notably the backwards step:</p>
<ul>
<li>(F-B 2) For all $k$, if $\Phi(k)$ is true, then $\Phi(k-1)$ is true</li>
</ul>
<p>This doesn&#39;t seem all that problematic, but while the natural numbers are unbounded upwards, they are bounded <em>downwards</em> by 0. From $\Phi(k)$, we get $\Phi(k-1)$, then further $\Phi(k-2)$, and so on until we get $\Phi(0)$. But from $\Phi(0)$ can we conclude $\Phi(-1)$? The backwards inductive step would certainly suggest so, but that&#39;s not how natural numbers work. In the AM-GM inequality above, what would it mean for it to hold for &quot;-1 numbers&quot;? It just doesn&#39;t make sense.</p>
<p>The difference here is that we <i>do</i> have an understanding that backwards induction terminates eventually at 0. In particular, what our backwards inductive statement really <em>should</em> say is that</p>
<ul>
<li>(F-B 2) For all $k\in \mathbb{N}$, if $\Phi(k+1)$ is true, then $\Phi(k)$ is true</li>
</ul>
<p>We first assume that $k \in \mathbb{N}$ before we apply it to our claim we&#39;re proving. But what if we didn&#39;t assume that?</p>
<p><strong>Proof by infinite descent</strong> exploits this assumption to make a very nice proof by contradiction. If we remove this condition assuming that one of our numbers is already a natural number, we could prove things by contradiction by showing that is a consequence. That is,</p>
<ul>
<li>(Suppose for contradiction that) $\Phi$ is true</li>
<li>If $m \in \mathbb{N}$ and $\Psi(m)$ is true, then $m-1 \in \mathbb{N}$ and $\Psi(m-1)$ is true </li>
</ul>
<p>Then you could conclude that $\Phi(n)$ <strong>is false</strong> for all $n \in \mathbb{N}$ since there is no infinitely descending sequence of natural numbers. $\Psi(n)$ here could be any consequence that would imply an infinitely decreasing sequence of natural numbers.</p>
<p>This is best done with an example.</p>
<hr>
<p><strong>Claim:</strong> If $\sqrt{k}$ is not an integer, then it is irrational.</p>
<p><strong>Proof:</strong> Suppose for a contradiction that there is a positive integer $k$ such that $\sqrt{k}$ is not an integer and not irrational, i.e. $\sqrt{k}$ is rational. So there are natural numbers $m,n \in \mathbb{N}$ such that $\sqrt{k} = \frac{m}{n}$. Now we can do some algebra on this expression:</p>
<center>
$
\begin{align}
\sqrt{k} &amp; = \frac{m}{n}
\newline
&amp; = \frac{m(\sqrt{k} - \lfloor \sqrt{k} \rfloor)}{n(\sqrt{k} - \lfloor \sqrt{k} \rfloor)}
\newline
&amp; = \frac{m\sqrt{k} - m\lfloor \sqrt{k} \rfloor}{n\sqrt{k} - n\lfloor \sqrt{k} \rfloor}
\newline
&amp; = \frac{(n\sqrt{k})\sqrt{k} - m\lfloor \sqrt{k} \rfloor}{n(\frac{m}{n}) - n\lfloor \sqrt{k} \rfloor}
\newline
\sqrt{k} &amp; = \frac{nk - m\lfloor \sqrt{k} \rfloor}{m - n\lfloor \sqrt{k} \rfloor}
\end{align}
$
</center>

<p>By multiplying by $\frac{\sqrt{k} - \lfloor \sqrt{k} \rfloor}{\sqrt{k} - \lfloor \sqrt{k} \rfloor} = 1$, we ended up with a new rational expression for $\sqrt{k}$. But notice, by definition of the floor function $\lfloor \cdot \rfloor$, we multiplied the numerator and denominator by $\sqrt{k} - \lfloor \sqrt{k} \rfloor &lt; 1$. So $m &gt; m(\sqrt{k} - \lfloor \sqrt{k} \rfloor) = nk - m\lfloor \sqrt{k} \rfloor$ and similarly for the denominator. But the numerator and denominator are both still natural numbers, since $m$, $n$, $k$, and $\lfloor k \rfloor$ are all natural numbers, so their sums and products are too!</p>
<p>So from a rational expression for $\sqrt{k} = \frac{m}{n}$, we found another equivalent rational expression with a strictly smaller numerator and denominator. So we could repeat this process again multiplying through by $\frac{\sqrt{k} - \lfloor \sqrt{k} \rfloor}{\sqrt{k} - \lfloor \sqrt{k} \rfloor}$ to find another smaller rational expression <em>ad infinitum</em>. But there are no infinitely decreasing sequences of natural numbers for the numerator and denominator to be a part of, giving us a contradiction.</p>
<p>So it must be that our initial assumption was wrong that there is a $\sqrt{k}$ that is neither and integer nor irrational. In other words, it for all natural numbers $k$, either $\sqrt{k}$ is an integer or it is irrational.</p>
<center>
$\blacksquare$
</center>

<p>Here&#39;s a <a href="http://xperimex.com/blog/grid-polygons/">geometric application of infinite descent</a> applied not to natural numbers directly, but rather integral multiples of a length of a line.</p>
<h2 id="multi-induction">Multi-Induction</h2>
<p>Let&#39;s revisit the very first inductive proof we gave. We showed that the formula for the sum of the first $n$ natural numbers is </p>
<center>

$\sum_{i=1}^n i = \large{\frac{n(n+1)}{2}}$

</center>

<p>There&#39;s a similar formula for a related double sum:</p>
<center>

$\sum_{j=1}^m \sum_{i=1}^n (i + j) = \large{\frac{mn(m+n+2)}{2}}$

</center>

<p>You might try to prove this with induction, but there&#39;s a sizeable difference between our original problems and this one: it&#39;s a formula of <strong>multiple variables</strong>.</p>
<p>As such, there is also a natural extension to what we&#39;ve been doing in <strong>multi-induction</strong>. A way to think of it is like the &quot;product&quot; of inductive arguments; if we were &quot;inducting linearly&quot; before, we&#39;ll now &quot;induct in a grid&quot;.</p>
<p>For our case of double induction, we&#39;ll represent our formula is true with $\Phi(m,n)$—just like what we did before with one variable. We&#39;ll then use the following formulation for double induction (DI): we&#39;ll show that</p>
<ul>
<li>(DI 1) $\Phi(1,1)$ is true</li>
<li>(DI 2) For all $m \geq 1$, show $\Phi(m,1)$ is true</li>
<li>(DI 3) For each fixed $m_0$ and for all $n \geq 1$, show that $\Phi(m_0, n)$ is true</li>
</ul>
<p>to prove that $\Phi(m,n)$ is true for all integers $m,n \geq 1$. If you think of $(m,n)$ as coordinates in space, (DI 2) is the &quot;horizontal&quot; induction, proving the claim along the $x$-axis and giving us the base cases for (DI 3), which fills in the columns along the $y$-axis.</p>
<p>And as you can probably guess, we&#39;ll show (DI 2) and (DI 3) with induction.</p>
<hr>
<p><strong>Claim:</strong> $\sum_{j=1}^m \sum_{i=1}^n (i + j) = \large{\frac{mn(m+n+2)}{2}}$</p>
<p><strong>Base Case:</strong> We&#39;ll check it for the case $m = n = 1$. $\sum_{j=1}^1 \sum_{i=1}^1 (i + j) = 2 = \frac{1 \cdot 1(1+1+2)}{2}$.</p>
<p><strong>Horizontal Inductive Hypothesis:</strong> We&#39;ll induct on $m$ and prove that the formula holds for all $m \geq 1$ while fixing $n=1$. So suppose the formula holds for some $m$, that is, $\sum_{j=1}^{m} \sum_{i=1}^1 (i + j) = \frac{m(m+3)}{2}$. We&#39;ll show that it also holds for $m+1$:</p>
<center>
$
\begin{align}
\sum_{j=1}^{m+1} \sum_{i=1}^1 (i + j) = \sum_{j=1}^{m+1} (1 + j) &amp; = \sum_{j=1}^{m} (1 + j) + (1 + m + 1)
\newline
&amp; = \frac{m(m+3)}{2} + (m + 2)
\newline
&amp; = \frac{m^2 + 5m + 4}{2}
\newline
&amp; = \frac{(m+1)(m+4)}{2}
\newline
&amp; = \frac{(m+1)((m+1) + 3)}{2}
\end{align}
$
</center>

<p>Since $\Phi(m,1) \Rightarrow \Phi(m+1,1)$, by induction, $\Phi(m,1)$ is true for all $m \geq 1$.</p>
<p><strong>Vertical Inductive Hypothesis:</strong> Horizontal induction now gives us the base cases we need to induct on $n$. We now know that for a fixed $m_0$, $\Phi(m_0, 1)$ is true, so that will act as our base case. Now assume that $\Phi(m_0,n)$ is true for some $n$. That is,</p>
<center>

$\sum_{j=1}^{m_0} \sum_{i=1}^n (i + j) = \large{\frac{m_{0} n(m_0+n+2)}{2}}$

</center>

<p>We will show that $\Phi(m_0, n+1)$ is also true. </p>
<center>
$
\begin{align}
\sum_{j=1}^{m_0} \sum_{i=1}^{n+1} (i + j) &amp; = \sum_{j=1}^{m_0}  \left( \sum_{i=1}^{n} (i + j) + (n+1 + j) \right)
\newline
&amp; = \sum_{j=1}^{m_0}  \sum_{i=1}^{n} (i + j) + \sum_{j=1}^{m_0} (n+1 + j)
\newline
&amp; = \frac{m_{0} n(m_0+n+2)}{2} + \sum_{j=1}^{m_0} (n+1 + j)
\newline
&amp; = \frac{m_{0} n(m_0+n+2)}{2} + \frac{m_0(m_0 + 1)}{2} + m_0(n+1)
\newline
&amp; = \frac{m_{0}(m_0 n + n^2 + 2n)}{2} + \frac{m_0(m_0 + 1 + 2(n + 1))}{2}
\newline
&amp; = \frac{m_{0}(m_0 n + n^2 + 2n + m_0 + 1 + 2(n + 1))}{2}
\newline
&amp; = \frac{m_0 (n + 1)(m_0 + (n+1) + 2)}{2}
\end{align}
$
</center>

<p>We get the 3rd line equality by the inductive hypothesis, the 4th line is just an arithmetic series, and the rest follow from algebra. Thus, $\Phi(m_0, n) \Rightarrow \Phi(m_0, n+1)$, and by induction, $\Phi(m_0,n)$ is true for a fixed $m_0$ and all $n \geq 1$.</p>
<p>But $m_0$ was arbitrary. So $\Phi(m,n)$ is true for all $m,n \geq 1$. In other words, for all $m,n \geq 1$,</p>
<center>

$\sum_{j=1}^m \sum_{i=1}^n (i + j) = \large{\frac{mn(m+n+2)}{2}}$

</br></br>

$\blacksquare$

</center>

<h2 id="transfinite-induction">Transfinite Induction</h2>
<p>In our original proofs of weak and strong induction, we relied primarily on the well-ordering of the natural numbers. Actually, that&#39;s really about all we cared about. Let&#39;s look again at our statement of (strong) induction from that proof:</p>
<hr>
<p><strong>Strong Induction:</strong> Let $S$ be a set of natural numbers with the following properties:</p>
<ol>
<li>$0 \in S$</li>
<li>If $0,1,\cdots,k \in S$, then $k+1 \in S$</li>
</ol>
<p>Then $S$ is the set of all natural numbers.</p>
<hr>
<p>Let&#39;s rewrite this with a bit more notation.</p>
<hr>
<p><strong>Strong Induction Again:</strong> Let $S \subseteq \mathbb{N}$ be a subset with the following properties:</p>
<ol>
<li>$0 \in S$</li>
<li>If $\forall m \leq k \ \ m \in S$, then $k+1 \in S$</li>
</ol>
<p>Then $S = \mathbb{N}$.</p>
<hr>
<p>If all that really mattered was the idea of $\mathbb{N}$ being well-ordered—this idea that there&#39;s a lesser element, or a &quot;next&quot; element in the set—what&#39;s stopping us from changing $\mathbb{N}$ with <em>any</em> set $A$ that is well-ordered under a relation $\leq$ (that is not necessarily &quot;less than or equal&quot;)? There is one issue though, that comes in the second clause for strong induction:</p>
<ol>
<li>If $\forall m \leq k \ \ m \in S$, then $k+1 \in S$</li>
</ol>
<p>Sometimes we can have well-ordered sets–that is have this concept of a &quot;next&quot; element—but have it such that there is no &quot;good&quot; definition of having a next, or $+1$ element. I know this sounds contradictory, but this will help if we talk it out from the start. So far we&#39;ve been working with the natural numbers, so that seems like a good place to work out of. But first, we need to understand what the natural numbers <em>are</em>. </p>
<h3 id="finite-ordinals">Finite Ordinals</h3>
<p>In general, we use the the natural numbers to <em>count</em> things, like the sizes of sets. So oftentimes, we do just that! Let&#39;s look at a construction of the natural numbers via sets that do exactly that (due to von Neumann):</p>
<p><strong>von Neumann&#39;s Construction of $\mathbb{N}$:</strong> We will define them recursively. </p>
<ul>
<li>$0 = \varnothing$</li>
<li>$n+1 = n \cup \{n\}$ (this is the <strong>successor</strong> of a number)</li>
</ul>
<p>So the first few natural numbers with this definition would be</p>
<center>
$
\begin{align}
0 &amp; = \varnothing
\newline
1 &amp; = 0 \cup \{0\} = \varnothing \cup \{\varnothing\} = \{\varnothing\}
\newline
2 &amp; = 1 \cup \{1\} = \{\varnothing\} \cup \{\{\varnothing\}\} = \{\varnothing, \{\varnothing\}\}
\newline
3 &amp; = 2 \cup \{2\} = \{\varnothing, \{\varnothing\}\} \cup \{\{\varnothing, \{\varnothing\}\}\} = \{\varnothing, \{\varnothing\}, \{\varnothing, \{\varnothing\}\} \}
\end{align}
$
</center>

<p>If it&#39;s easier, you can also think of each number being defined as the set of all previous numbers, meaning that $n+1 = \{0, 1, \cdots, n\}$. So the number, say $4$, could be thought of as how many numbers are in the set $\{0,1,2,3\}$. If you&#39;re interested, you can look into how to do all the <a href="https://math.stackexchange.com/questions/1135354/how-to-perform-arithmetic-4-functions-on-von-neumann-numbers">standard arithmetic with these set operations</a>, but the only point that we care about is how we can compare them. </p>
<p>Since we&#39;re working with sets, the idea of &quot;less than or equal&quot; doesn&#39;t really make sense, but fortunately, we built into our definition a nice counterpart to represent &quot;less than or equal&quot;. Our well-ordering relation is &quot;contains&quot; $\in$: for two numbers, if $a \in b$, then we have $a &lt; b$. This can be seen easiest with the second definition of a number being the set of all previous numbers. We call these numbers that relate to each other in this set-theoretic way as <strong>ordinals</strong>. In particular,</p>
<ul>
<li>Ordinals are well-ordered under the relation $\in$, and</li>
<li>Ordinals also have the property that whenever $x \in S$, it&#39;s also the case that $x \subseteq S$ as well. </li>
</ul>
<p>Ordinals generalize the way we would normally count things to infinite sizes. The natural numbers are also known as the <strong>finite ordinals</strong>.</p>
<p>So every natural number can be identified with the set of all natural numbers before it. And the set of all these finite ordinals are well-ordered, and we can do induction on them like we have been doing before. Great!</p>
<h3 id="infinite-ordinals">Infinite Ordinals</h3>
<p>But look at our definition of an ordinal. We&#39;re defining them in this recursive manner, but there&#39;s nothing saying that they have to be of finite size. So what happens if we just make an infinite ordinal? So far all of our ordinals have been of finite natural numbers, what&#39;s stopping us from extending one of these sets to infinity?</p>
<p>Well, suppose we did take the limit of the set of natural numbers. That is the set, let&#39;s call $\omega$, defined as</p>
<center>

$\omega = \{0,1,2,3,4,\cdots\}$

</center>

<p>This set is certainly greater than any other natural number under the relation $\in$—in fact, it is the <strong>supremum</strong> of the natural numbers, being the smallest ordinal greater than all of the natural numbers. Also, certainly by the way we defined the natural numbers, every element of $\omega$ is also a subset of $\omega$, so $\omega$ fits the definition of an ordinal too.</p>
<p>But think about that for a second. If we take the set of all natural numbers alongside this <strong>infinite ordinal</strong> in the set $\mathbb{N} \cup \{\omega\}$, we definitely have a well-ordered set, but how could we ever do induction on this set? Because $\omega$ is greater than all natural numbers, it definitely does not have the form of $k+1$ for some natural number $k$. Yet, according to our definition of induction</p>
<ul>
<li>(SPMI 2) If $\forall m \leq k \ \ m \in S$, then $k+1 \in S$</li>
</ul>
<p>those are the only statements we could build off of. No matter how long you let our induction go for, it will never be able to prove a statement is true for the ordinal $\omega$, while still being in a well-ordered set.</p>
<p>This is the purpose of <strong>transfinite induction</strong>. When working to prove things for any well-ordered set, we can run into these <strong>limiting cases</strong> ($\omega$ is aptly called a <strong>limiting ordinal</strong>) that don&#39;t work completely well with the notion of having a &quot;next element&quot; at infinity; you can imagine labelling elements in a well-ordered set as with 0, 1, 2, etc. as we have been doing before, and then eventually running into an element $\omega$ to throw your induction off. It&#39;s always infinity that makes things a little more difficult.</p>
<h3 id="the-principle-of-transfinite-induction">The Principle of Transfinite Induction</h3>
<p>The principle of transfinite induction will look extremely familiar to what we&#39;ve already been doing.</p>
<p><strong>Transfinite Induction:</strong> Let $A$ be a well-ordered set, and $\Phi(x)$ be a proposition that has domain $A$ with the following properties:</p>
<ul>
<li>(TI 1) $\Phi(0)$ is true</li>
<li>(TI 2) $\Phi(b)$ is true for all $b &lt; a$, then $\Phi(a)$ is true</li>
</ul>
<p>Then you can conclude that $\Phi(x)$ is true $\forall x \in A$.</p>
<p>$0$ just means the least element of $A$. The only real difference again is in the inductive step. In (TI 2), we replace the idea of having $k+1$ with just a notion of &quot;greater than&quot; as to deal with possible limiting cases. In fact, transfinite induction is presented <em>as normal induction</em> with an additional condition:</p>
<hr>
<p><strong>Transfinite Induction:</strong> Let $A$ be a well-ordered set, and $\Phi(x)$ be a proposition that has domain $A$ with the following properties:</p>
<ul>
<li>(TI 1: <strong>Base Case</strong>) $\Phi(0)$ is true</li>
<li>(TI 2a: <strong>Successor Case</strong>) If $\Phi(\beta)$ is true for all $\beta \leq \alpha$, then $\Phi(\alpha+1)$ is true</li>
<li>(TI 2b: <strong>Limiting Case</strong>) $\Phi(\beta)$ is true for all $\beta &lt; \alpha$, then $\Phi(\alpha)$ is true</li>
</ul>
<p>Then you can conclude that $\Phi(x)$ is true $\forall x \in A$.</p>
<hr>
<p>(TI 2a) is essentially just the normal form of (strong) induction we&#39;ve come to know and love, with the only difference being that we can have successor ordinals that are not natural numbers, like $\omega + 1$. So it really is just the limiting cases that can throw a wrench into our proofs.</p>
<p>Let&#39;s now put it to work.</p>
<h3 id="examples">Examples</h3>
<p><a href="https://math.wvu.edu/~kciesiel/Other/ElectronicReprints/B2IntSetThe.pdf"><strong>Claim:</strong></a> There is a subset $A \subset \mathbb{R}^2$ that intersects <em>every</em> line in exactly two points.</p>
<p>This is not clear to me at all. I mean, just by literally the sheer number of lines there are, it seems hard to make it so that you can nudge points around so that no three are ever collinear, while still somehow covering every line. We can uniquely identify every line with an equation $y = ax + b$, so we can identify every line with an ordered pair $(a,b)$. Thinking of this as coordinates, it should be clear that the number of lines is equivalent to the size of $\mathbb{R}^2$, which is more than the number of natural numbers. So if we want to prove this via induction, we&#39;ll need to do so with transfinite induction.</p>
<p><strong>Proof:</strong> Let $\{ L_\alpha \}$ be a labelling of every line (i.e. assign every line an ordinal $\alpha$). We&#39;ll inductively construct a sequence $\{A_\alpha\}$ of subsets of $\mathbb{R}^2$ with the following properties for each $\alpha$:</p>
<ul>
<li>(Instantiation) $A_\alpha$ has at most two points</li>
<li>(Preservation) $\bigcup_{\beta \leq \alpha} A_\beta$ contains no three points collinear</li>
<li>(Diagonal) $\bigcup_{\beta \leq \alpha} A_\beta$ contains exactly two points of $L_\alpha$</li>
</ul>
<p>Then $A = \bigcup A_\alpha$ over all ordinals $\alpha$ will have the desired property. This is because the <em>preservation property</em> will ensure every line has at most two points in $A$, while the <em>diagonal property</em> will ensure that every line has at most two points in $A$.</p>
<p><strong>Base Case:</strong> $\alpha = 0$. $L_0$ would be our first line, and all we need to do to satisfy those 3 properties above is let $A_0$ be any two points in $L_0$.</p>
<p><strong>Successor Case:</strong> Suppose for any ordinal $\alpha$, the sequence $\{A_\beta\}_{\beta \leq \alpha}$ satisfies the 3 properties above. We&#39;ll show that we can construct a satisfactory $A_{\alpha + 1}$ to extend the sequence.</p>
<p>Let $B = \bigcup_{\beta \leq \alpha} A_{\beta}$, and $C$ be the set of all lines that contain two points from $B$. By the inductive hypothesis, $B$ has the preservation property, so line $L_{\alpha + 1}$ has at most 2 points in $B$, i.e. $L_{\alpha + 1} \cap B$ has at most 2 points. Now we have two cases to consider.</p>
<p><em>Case 1:</em> If $L_{\alpha + 1} \cap B$ has exactly 2 points, we just let $A_{\alpha+1} = \varnothing$ to immediately satisfy the 3 properties.</p>
<p><em>Case 2:</em> If $L_{\alpha + 1} \cap B$ has less than 2 points, then line $L_{\alpha+1}$ intersects every line in $C$ in at most 1 point (if it intersected a line in more than 1 point, it would be that line itself), i.e. for all lines $L \in C \ \ |L_{\alpha+1} \cap L| \leq 1$. To satisfy the preservation and diagonal property, we obviously want to pick a point in $L_{\alpha + 1} \backslash \bigcup C$ (i.e. a point on our new line but not on any of the previous lines). We can do this for sure since we can show $L_{\alpha + 1} \backslash \bigcup C \neq \varnothing$.</p>
<ul>
<li>The set of all points in a line has equivalent cardinality to the reals (it&#39;s just a tilted number line, after all). So $|L_{\alpha + 1}| = |\mathbb{R}| = 2^{\aleph_0}$.</li>
<li>Every line can be uniquely written as $y = ax+b$, and thus also be identified by the ordered pair $(a,b)$. So the number of lines is equivalent to $|\mathbb{R}^2| = 2^{\aleph_0}$</li>
<li>$C$ is the set of all lines with two points from $B$, which by definition, does not include all lines yet. So $|C| &lt; 2^{\aleph_0}$</li>
<li>Using the fact that for all lines $L \in C \ \ |L_{\alpha+1} \cap L| \leq 1$:<center>
$|L_{\alpha + 1} \cap \bigcup C| = |\bigcup_{L \in C} L_{\alpha + 1} \cap L| \leq |C| &lt; 2^{\aleph_0}$
</center></li>
<li>So $L_{\alpha + 1}$ and $\bigcup C$ share fewer than $2^{\aleph_0}$ elements, together, meaning that $L_{\alpha + 1} \backslash \bigcup C \neq \varnothing$.</li>
</ul>
<p>Now we&#39;re free to pick a subset from $A_{\alpha + 1} \subset L_{\alpha + 1} \backslash \bigcup C$. If $L_{\alpha + 1} \cap B$ has one point, just pick 1 point for $A_{\alpha + 1}$, and if $L_{\alpha + 1} \cap B$ has no points, then let $A_{\alpha + 1}$ 2 points. This will satisfy our preservation and diagonal properties.</p>
<p><strong>Limit Case:</strong> Suppose for any ordinal $\alpha$, and for all $\gamma &lt; \alpha$, the sequence $\{A_\gamma\}_{\beta \leq \gamma}$ satisfies the 3 properties above. We want to show that we can construct a $A_{\alpha}$ to extend the sequence. Notice in our successor argument, we never really needed the fact that we were proving it for $A_{\alpha + 1}$, but just the fact that we had a series of already constructed previous cases of $A_\beta$ with $\beta &lt; \alpha + 1$. This makes our limit case almost identical to the successor case. Here&#39;s the outline:</p>
<ul>
<li>Let $B = \bigcup_{\gamma &lt; \alpha} A_\gamma$, and $C$ be the set of all lines that contain two points from $B$</li>
<li>Now consider the set $L_\alpha \cap B$</li>
<li>$L_\alpha \cap B$ contains at most 2 points because $\{A_\gamma\}_{\beta \leq \gamma}$ has the preservation property</li>
<li><em>Case 1:</em> If $L_\alpha \cap B$ contains 2 points, let $A_{\alpha} = \varnothing$</li>
<li><em>Case 2:</em> If $L_\alpha \cap B$ contains less than 2 points, then $L_{\alpha}$ intersects with every line in $C$ at most once<ul>
<li>By the same reasoning as before we can pick a subset $A_{\alpha} \subset L_{\alpha} \backslash \bigcup C \neq \varnothing$</li>
<li>If $L_\alpha \cap B$ has 1 point, let $A_{\alpha}$ be 1 point</li>
<li>If $L_\alpha \cap B$ has 0 points, let $A_{\alpha}$ be 2 points</li>
</ul>
</li>
</ul>
<p>Now again let $A = \bigcup A_\alpha$ over all ordinals $\alpha$. By transfinite induction, we&#39;ve shown there is a subset $A \subset \mathbb{R}^2$ that intersects every line exactly twice.</p>
<center>
$\blacksquare$
</center>

<p>Outside of set theory, because there are more reals than natural numbers, transfinite induction lends itself to these types of weird geometry problems.</p>
<p>Though, I have to admit I did lie a little bit here. We technically used <strong>transfinite recursion</strong> as opposed to transfinite induction. We didn&#39;t necessarily prove a claim for all ordinals $\alpha$, but rather <strong>constructed</strong> something inductively/recursively over the ordinals that satisfied some properties. The difference is subtle, but they are technically different methods from one another. Maybe you could argue that we were proving the claim that <em>&quot;there is something constructible&quot;</em> for all ordinals, so I find the difference nitpicky.</p>
<p>Examples of transfinite induction can be tedious (especially if uncomfortable with ordinals and working with infinities), but you can find some in <a href="https://math.wvu.edu/~kciesiel/Other/ElectronicReprints/B2IntSetThe.pdf">this book</a> for more. Some interesting examples include:</p>
<ul>
<li>There is a countable partition of $\mathbb{R^2}$ so that the distance between any two different points in the same set is irrational </li>
<li>$\mathbb{R^2}$ <em>is not</em> a union of disjoint circles</li>
<li>$\mathbb{R^3}$ <i>is</i> a union of disjoint circles</li>
</ul>
<h2 id="structural-induction">Structural Induction</h2>
<p>The idea of well-ordering—a key idea in &quot;climbing a ladder&quot;—naturally led us to generalize induction to transfinite induction. But there&#39;s something else in our idea of induction that, to me at least, seems more characteristic to the proof technique: <strong>recursion</strong>.</p>
<p>We&#39;ve already seen recursion a little bit, but this idea of <strong>defining things within themselves</strong> is what induction really screams to me. In that second clause of our principle,</p>
<ul>
<li>(PMI 2) $\forall k \geq 0$, if $\Phi(k)$ is true, then $\Phi(k+1)$ is true</li>
</ul>
<p>we rely on proving the validity of $\Phi(k+1)$ by already assuming the &quot;simpler&quot; idea $\Phi(k)$. How do we know $\Phi(k)$ is valid? We show it from the &quot;simpler&quot; $\Phi(k-1)$. And we keep going until we hit the simplest version of our claim with our base case $\Phi(0)$.</p>
<p>Building up examples from a simplest case is what I think of when I use induction. But, there are many other times we build something from a base or simple case, too. <strong>Trees</strong>, in computer science and graph theory, follow this exact pattern of construction. </p>
<p><div id="example_tree" style="flex: 2; position: relative;"></div></p>
<script src="/js/compactness/example_tree.js"></script>

<!-- https://www.desmos.com/calculator/g6qtogsmbe -->
<p>We have a <strong>root</strong> at the top that brances out into different leaves and paths. While we may not have a definite &quot;next&quot; element going down a tree, we certainly have this recursive nature where at each step going down a tree, we have a smaller, &quot;simpler&quot;, subtree. So perhaps, if we wanted to prove somthing about trees, there&#39;s a type of inductive argument we could use that modifies our original idea. For a propsition (like a property) $\Phi$ about a recursively defined structure like a tree, we could have somthing like</p>
<ul>
<li>Show $\Phi$ is true for the base case of the structure</li>
<li>If $\Phi$ holds for all substructures, then $\Phi$ also holds for the recursively defined structure</li>
</ul>
<p>then we should be able to conclude that $\Phi$ holds for the entire structure. This type of <strong>structural induction</strong> is something that should make sense based on our previous, regular versions of induction, but it&#39;s something so general we&#39;ll have to adapt it to our structures.</p>
<p>Here&#39;s a simple example building on trees. First, we need some definitions.</p>
<ul>
<li>A <strong>vertex</strong> is a dot in our tree.</li>
<li>An <strong>edge</strong> is a line that connects two vertices</li>
</ul>
<p>We define a <strong>tree</strong> recursively:</p>
<ul>
<li>(Base Case) A tree has a root vertex with no edges, or</li>
<li>(Recursive Definition) A tree has a root vertex with edges connecting to some number of other trees</li>
</ul>
<hr>
<p><strong>Claim:</strong> For our tree, let $V$ be the set of vertices and $E$ the set of edges. Then $|V| = |E| + 1$.</p>
<p><strong>Base Case:</strong> Our base case is a tree is a root vertex with no edges. So $|V| = 1$, and $|E| = 0$, so the claim holds.</p>
<p><strong>Inductive Hypothesis:</strong> Suppose that we have a tree with $n$ subtrees, and the claim holds for all subtrees. We will use $V_i$ and $E_i$ to denote the set of vertices and edges respectively for tree $i=1,\cdots,n$.</p>
<p>Then by definition, the number of vertices of the whole tree </p>
<center>
$|V| = 1 + |V_1| + |V_2| + \cdots + |V_n|$
</center>

<p>as the tree is built from a root vertex connected to the subtrees. Similarly, </p>
<center>
$|E| = n + |E_1| + |E_2| + \cdots + |E_n|$ 
</center>

<p>as the number of edges would be the sum of the edges of the subtrees plus the additional $n$ edges that connect the subtrees to the root. Now it&#39;s just a matter of algebra with the inductive hypothesis.</p>
<center>
$
\begin{align}
|V| &amp; = 1 + |V_1| + |V_2| + \cdots + |V_n|
\newline
&amp; = 1 + (|E_1| + 1) + (|E_2| + 1) + \cdots (|E_n| + 1)
\newline
&amp; = 1 + (n + |E_1| + |E_2| + \cdots + |E_n|)
\newline
&amp; = 1 + |E|
\end{align}
$
</center>


<center>
$\blacksquare$
</center>

<hr>
<p>Here&#39;s another one with recursively defined sets.</p>
<p><strong>Claim:</strong> Define the set $S$ as follows:</p>
<ul>
<li>(Base) $6,21 \in S$</li>
<li>(Recursive) If $x,y \in S$, then $x + y \in S$</li>
</ul>
<p>Show that every element in $S$ is a multiple of 3.</p>
<p><strong>Base Case:</strong> Clearly $6 = 3 \cdot 2$ and $21 = 3 \cdot 7$ are both multiples of 3</p>
<p><strong>Inductive Hypothesis:</strong> Assume that $x,y \in S$ and both are multiples of 3 i.e. $x = 3n$ and $y = 3m$ for integers $n,m \in \mathbb{Z}$. Then $x + y = 3(n + m)$ which is also a multiple of 3. So clearly all elements are multiples of 3. $\ \blacksquare$</p>
<hr>
<p>Finally, one more from <a href="http://xperimex.com/blog/intro-logic/#-mathcal-l-_1-a-first-attempt">propositional logic</a>. In propositional logic, we define sentences recursively with connectives. These and only these are sentences:</p>
<ul>
<li>(Base) Sentence letters $P, Q, R, \cdots$ are sentences</li>
<li>(Recursive) If $\phi$ and $\psi$ are sentences then the following are also sentences:<ul>
<li>$\neg \phi$ (negation)</li>
<li>$(\phi \wedge \psi)$ (and)</li>
<li>$(\phi \vee \psi)$ (or)</li>
<li>$(\phi \rightarrow \psi)$ (material implication)</li>
<li>$(\phi \leftrightarrow \psi)$ (biconditional)</li>
</ul>
</li>
</ul>
<p><strong>Claim:</strong> All sentences have an equal number of left and right parantheses.</p>
<p><strong>Base Case:</strong> Sentence letters have no parantheses, and $0=0$, so they have an equal number of left and right parantheses.</p>
<p><strong>Inductive Step:</strong> Suppose $\phi$ and $\psi$ are sentences with an equal number of left and right parantheses. We check the claim for each connective:</p>
<ul>
<li>$\neg \phi$: Since we add no new parantheses and $\phi$ has an equal amount of left and right, the claim holds.</li>
<li>$(\phi \wedge \psi)$: If $\phi$ has $n$ left and right parantheses, and $\psi$ has $m$, then $\phi \wedge \psi$ has $n+m$ left and right parantheses, still being equal. Adding parantheses around it keeps the equality, just adding 1 to each side.</li>
<li>The remaining connectives are identical to the $\wedge$ case</li>
</ul>
<center>
$\blacksquare$
</center>

<hr>
<p>Structural induction is a fairly straightforward adaptation of induction, and, as a proof technique, is helpful to formalize what might otherwise just be obvious facts (like the above). </p>
<p>Induction was something we only limited to well-ordered sets. Structural induction allows us to use it on <strong>well-founded partial orderings</strong> too. Well-founded is similar to well-ordered, meaning that given a relation $R$ on a set $X$, every non-empty subset has a minimal element. A partial order is a relation $R$ on a set $X$ that relates elements in a set $X$ to one another, but without necessarily comparing all elements to each other. Going back to the example of trees, we can relate elements by being in the same chain of edges, so different branches would be uncomparable to one another.</p>
<h1 id="continuous-induction">Continuous Induction</h1>
<p>Up until now, we&#39;ve treated induction as an inherently <strong>discrete method</strong>. I mean, how can it not be? We started by first describing a method that is iterating over the natural numbers, and then further generalized them to any well-ordered set. But nonetheless, we only applied induction to inherently <em>discrete</em> casees. What would it even mean to climb a &quot;continuous&quot; ladder? What would a &quot;next step&quot; look like? For any real number $x$ and some incremental value $\delta$, there&#39;s always a number $y$ in between $x &lt; y &lt; x + \delta$, so the real numbers don&#39;t give us this nice &quot;next step&quot; to prove (with this, it shouldn&#39;t be hard to see that the real numbers aren&#39;t even well-ordered).</p>
<p>Let&#39;s think about what we&#39;re doing when we use induction. It sort of feels like an almost constructive method, right? We first show there is at least one element in our set with our base case. Then from our base case, we <em>add</em> another element through the inductive step. From that new element, we <em>add</em> another element with another inductive step. And so on and so on. We treat induction like a <em>method</em> in which we add more and more elements to our set.</p>
<p>This is inherently rooted in thinking in terms of an <strong>indexed</strong> claim $\Phi(n)$. If we want to continue this analogy, we really need a way of thinking that gives us a new &quot;next step&quot;. Let&#39;s revisit our definition of induction when we were proving it from well-ordering:</p>
<hr>
<p><strong>Principle of Mathematical Induction:</strong> Let $S \subseteq \mathbb{N}$ be a subset with the following properties:</p>
<ol>
<li>$0 \in S$</li>
<li>If $k \in S$, then $k+1 \in S$</li>
</ol>
<p>Then $S = \mathbb{N}$.</p>
<hr>
<!-- Again, we could define $S = \\{ n \in \mathbb{N} \ | \ \Phi(n) \  \textrm{is true} \\}$, but the key point is to think in terms of these **properties**. If $S$ satisfies those two properties, then $S$ isn't a subset of $\mathbb{N}$, but rather $S = \mathbb{N}$. It's not that we're adding elements to $S$, but rather all those _elements were already in_ $S$, by having those properties. -->
<p>Again, we could define $S = \{ n \in \mathbb{N} \ | \ \Phi(n) \  \textrm{is true} \}$, but the clear issue is still our inductive step. What will be our &quot;next step&quot;, or $k+1$? Well, if there&#39;s no good indexing of the reals and we can&#39;t include any particular one inductive step, why don&#39;t we just include a bunch? As in, why don&#39;t we just include a new <strong>subset</strong> of numbers at each inductive step? What could be wrong with that? Our induction then would be that if we can show that some number $x \in S$, then we can show that some <em>further interval</em> is also in $S$, as opposed to just a single other number. That way we can just keep adding more and more interval until we reach as many reals as we want!</p>
<hr>
<p><strong>Real Induction Attempt 1:</strong> Let $S \subseteq \mathbb{R}_{\geq 0}$ be a subset with the following properties:</p>
<ol>
<li>$0 \in S$</li>
<li>For any $x \geq 0$, if $x \in S$ then $[x, z) \subseteq S$ for some $z &gt; x$</li>
</ol>
<p>Then $S = \mathbb{R}_{\geq 0}$.</p>
<hr>
<p>Instead of dominoes, our analogy would be like improvising a rope: so long as you have smaller threads that have some length, you can eventually tie a rope as long as you want.</p>
<p>There is one problem with our formulation, though: it doesn&#39;t ensure a certain size for our intervals. So if our intervals are shrinking in length, they might converge onto only some smaller part of the real line. Say we start at 0, but at each step $n$ only add an interval of length $(\frac{1}{2})^n$. Then we&#39;ll only cover the reals from $[0,1)$. So we need at least one more requirement for this to work.</p>
<p>And actually, we have run into this issue before. Recall for transfinite induction, we had limit ordinals that blocked our path, and had to prove the limiting cases in addition to the inductive step. We will do the same here.</p>
<hr>
<p><a href="https://arxiv.org/pdf/1208.0973.pdf"><strong>Real Induction:</strong></a> Let $S \subseteq \mathbb{R}_{\geq 0}$ be a subset with the following properties:</p>
<ul>
<li>(RI 1) $0 \in S$</li>
<li>(RI 2) For any $x \geq 0$, if $[0,x] \subseteq S$ then $[x, z] \subseteq S$ for some $z &gt; x$</li>
<li>(RI 3) For any $x \geq 0$, if $[0,x) \subseteq S$ then $x \in S$</li>
</ul>
<p>Then $S = \mathbb{R}_{\geq 0}$.</p>
<hr>
<p>So now if we run into a limit case like before, we say it must be in our set, and that gives us a new case to continue performing real induction on. One other thing to note is that I tweaked our second condition (RI 2) to be closer to the strong form of induction from before to highlight there is an equivalent analogy in real induction. I also changed (RI 2) to be a closed interval, as our new (RI 3) allows us to do that. If a set $S$ satisfies (RI 1–3), we say $S$ is <strong>inductive</strong>.</p>
<p>So <strong>real induction isn&#39;t all that different from what we&#39;re used to already</strong>. Instead of natural numbers being our cases, intervals are. We start with a base case, and slowly show our claim holds on new intervals until we end up showing that from combining all those intervals, the claim actually holds for all real numbers.</p>
<p>You might be wondering how this is at all useful. Particularly because of (RI 2): we no longer have a concrete $k+1$ we can work with in our proofs. Instead, we&#39;re stuck with this weird existence proof we have to find that doesn&#39;t seem tangible at all in practice. That&#39;s what I, at least, thought at first. Fortunately, much of real analysis has built into their definitions this same ambiguous existence-of-a-number that we can leverage (as you&#39;ll see).</p>
<p>Earlier I pointed out how we might run into the &quot;issue&quot; of only proving a claim for the interval $[0,1)$, but sometimes that&#39;s exactly what we want as opposed to showing something for all reals. We can slightly modify our method of induction just by limiting our choices of possible elements:</p>
<hr>
<p><strong>Interval Induction:</strong> Let $S \subseteq [a,b]$ be a subset with the following properties:</p>
<ul>
<li>(RI 1) $a \in S$</li>
<li>(RI 2) For any $a \leq x &lt; b$, if $[a,x] \subseteq S$ then $[x, z] \subseteq S$ for some $z &gt; x$</li>
<li>(RI 3) For any $a &lt; x \leq b$, if $[a,x) \subseteq S$ then $x \in S$</li>
</ul>
<p>Then $S = [a,b]$.</p>
<hr>
<p>All we did is change our base case, and add a cap to our inductive step.</p>
<p>While we&#39;re here, we might as well check beyond our intuition that this should work.</p>
<p><strong>Proof of Real Induction:</strong> Suppose a set $S \subseteq [a,b]$ is inductive, and (RI 1–3) hold. We want to show that $S = [a,b]$. So—just like in our proof of regular induction—suppose for contradiction, $S \neq [a,b]$, so there is a non-empty set $T = [a,b] \backslash S \neq \varnothing$. Since $T$ is bounded, and by the completeness of the reals, $T$ has an infimum (greatest lower bound).</p>
<ul>
<li><strong>Case 1:</strong> $\mathbf{\inf (T) = a}$. By (RI 1), $a \in S$. By (RI 2), there is a $z &gt; a$ such that $[a,z] \subseteq S$. So $z$ is a lower bound for $T$ (the elements not in $S$). But $z &gt; a = \inf (T)$, contradicting the definition of an infimum.</li>
<li><strong>Case 2:</strong> $\mathbf{a &lt; \inf(T) \in S}$. $\inf(T) \neq b$, since we declared $T$ non-empty. Then by (RI 2), there is a $z &gt; \inf(T)$ such that $[\inf(T), z] \subseteq S$. Like before, this would suggest $z &gt; \inf(T)$ is a lower bound for $T$, contradicting the definition of an infimum.</li>
<li><strong>Case 3:</strong> $\mathbf{a &lt; \inf(T) \in T}$. Then by definition of $T$, we would have $[a,\inf(T)) \in S$. By (RI 3), then $\inf(T) \in S$, which is again a contradiction by definition of $T$.</li>
</ul>
<p>Since these 3 cases are exhaustive for the infimum of $T$, and all lead to a contradiction, it must be the case that our initial assumption is wrong. That is, that $S \neq [a,b]$. In other words, if (RI 1–3) hold on our desired interval, it must be that $S = [a,b]$.</p>
<center>
$\blacksquare$
</center>

<p>So now we have this method of showing a claim holds for more and more subintervals that build on each other, until it completes <em>the whole interval</em>, allowing us to prove theorems in a now more familar way than before.</p>
<p>Here&#39;s a nice intuitive example.</p>
<p><strong>Intermediate Value Theorem:</strong> Suppose $f:[a,b] \rightarrow \mathbb{R} \backslash \{0\}$ is continuous, and $f(a) &gt; 0$. Then $f(b) &gt; 0$.</p>
<p>If $f(x)$ is continuous and only maps numbers to non-zero real numbers, then it should make sense that if we have a point $a$ where $f(a) &gt; 0$, then we should not have <em>any</em> number where $f(x) \leq 0$ without &quot;lifting up our pen&quot;; since $f(x) \neq 0$, we have this barrier where either our function is continuous and positive, or it is not continuous and negative too. </p>
<p>The idea of this proof is to use continuity to inductively string together intervals that are positive on $f$ until we cover the whole length of $[a,b]$. Just for consistency, the set we&#39;re secretely working with (as from our statement of real induction) is $S = \{x \in [a,b] \ | \ f(x) &gt; 0\}$.</p>
<p><strong>Base Case:</strong> From our assumption, we&#39;re already given that $f(a) &gt; 0$.</p>
<p><strong>Inductive Hypothesis:</strong> Say that for some $a \leq x &lt; b$ that $f(t) &gt; 0$ for all $t \in [a,x]$. We want to show that there is a further interval $z &gt; x$ where $f(t) &gt; 0$ for all $t \in [x,z]$.</p>
<p>Since $f$ is continuous at $x$, there is a small neighborhood centered at $x$ with also positive outputs i.e. $\exists \delta &gt; 0$ such that for all $t \in (x-\delta, x+\delta)$ we have $f(t)&gt;0$. You can just check this with the definition of continuity. A function $f:E \rightarrow \mathbb{R}$ is continuous at $x$ if:</p>
<center>
$\forall \epsilon &gt; 0 \ \exists \delta &gt; 0 \ \forall p \in E \ \ \left( |x-p| &lt; \delta \Rightarrow |f(x) - f(p)| &lt; \epsilon \right)$
</center>

<p>So if we let $\epsilon &lt; f(x)$, we get some corresponding $\delta$ so that $f(p)&gt;0$ for $p$ in that neighborhood. Thus, if we let $z = x + \delta$, we&#39;ve proven our inductive step that there is a number $z &gt; x$ such that $f(t) &gt; 0$ for all $t \in [x,z]$. It might be a small interval, but good enough nonetheless.</p>
<p><strong>Limit Case:</strong> Now say for for some $a &lt; x \leq b$, we have that $f(t) &gt; 0$ for all $t \in [a,x)$. We need to show that $f(x) &gt; 0$ as well. Suppose it wasn&#39;t, i.e. $f(x) \leq 0$. By definition of our function, $f(x) \neq 0$, so the only remaining case is $f(x) &lt; 0$. But by continuity—like in the inductive step—there would be a neighborhood such that $f(t) &lt; 0$ for all $t \in (x - \delta, x + \delta)$. But that contradicts our assumption that $f(t) &gt; 0$ for all $t \in [a,x)$ as $x - \delta &lt; x$. So it must be the case that $f(x) &gt; 0$.</p>
<p>By real induction, we have proven that if $f:[a,b] \rightarrow \mathbb{R} \backslash \{0\}$ is continuous and $f(a) &gt; 0$, then $f(x) &gt; 0$ for all $x \in [a,b]$. And in particular, $f(b) &gt; 0$. </p>
<center>
$\blacksquare$
</center>

<p>For more examples, I&#39;d read the <a href="https://arxiv.org/pdf/1208.0973.pdf">instructional paper</a> I linked above that goes quite in-depth in proving many famous theorems with real induction. Most of the proofs are relatively straightforward once you figure out how to state your set in a good way to induct on it.</p>
<p>Real induction is one of those tools that just doesn&#39;t seem like it should work by the way we treat normal induction. It&#39;s not a method one would probably think of, and given how little it&#39;s used, it&#39;s not surprising it&#39;s not even that well-known.</p>
<h1 id="conclusion">Conclusion</h1>
<p>Induction is one of the most fundamental tools in math. It&#39;s inextricably linked to our modern conception of the natural numbers, and in many ways, is what sets apart our contemporary understanding of math from other logical systems. So, I&#39;m not surprised it&#39;s as powerful a proof tool as it is, but there is so much more to it than the typical weak and strong induction that is primarily taught. How we apply induction gives us so many new and creative ways to prove claims, but more importantly how thinking inductively naturally guides our intuition for alternate approaches. We saw it first with transfinite induction, then real induction, but who knows what other powerful variations on induction there may be.</p>
]]></description>
         <link>http://xperimex.github.io/blog/real-induction</link>
         <guid isPermaLink="true">http://xperimex.github.io/blog/real-induction</guid>
         <dc:creator><![CDATA[Adi Mittal]]></dc:creator>
      </item>
      <item>
         <title><![CDATA[Privacy Protection and Zero-Knowledge Proofs]]></title>
         <description><![CDATA[Your password is not protected perfectly, but it's good enough. 

 <p>Proofs, to me, are the cornerstones of all science. What separates math, physics, chemistry, and all other fields of science is the level of rigor we expect for professionals to conduct themselves. We don&#39;t take anything for fact until we are convinced irrefutably to call it so. We can conjecture all we want, but it only holds so much sway until we can use it as a definitively true claim. Mathematics is even more strict in how it&#39;s a purely deductive field, where the notion of a proof accepts nothing but a direct chain of deductive, causal reasoning. Sure, even in math sometimes we use empirical data to guide our judgements, but <a href="https://math.stackexchange.com/questions/514/conjectures-that-have-been-disproved-with-extremely-large-counterexamples">&quot;proof by lack of a counterexample&quot; isn&#39;t all that helpful</a>.</p>
<p>But in the day-to-day, we rarely care for such rigor. If the weather man says it&#39;s going to rain today, I&#39;m inclined to believe it since he&#39;s <em>mostly</em> been right before, and that&#39;s good enough for me. &quot;Proof&quot;, to most people, usually just refers to any kind of persuasive evidence, as opposed to air-tight arguments. You want to be <em>convinced</em> with proof—nothing more, nothing less. If someone tells me they&#39;re a Michelin star chef, I won&#39;t need to see the certificate, but rather I&#39;ll probably be convinced if they even make one meal for me up to that standard.</p>
<p>Indirect proof to validate something, like with the case of the Michelin star chef, is what we usually rely on. We can&#39;t always provide hard evidence all the time, so convincing others with a demonstration of sorts is a nice alternative. But sometimes, it is the <em>only</em> option. If you had to prove citizenship to a country, sending over all your legal documents in one package, to one person, seems like a risky idea. If that package is lost or intercepted, your identity is gone. Or perhaps you are voting in an election, and want to prove that you did in fact vote. But ideally you could do that without having to disclose exactly who you voted for.</p>
<p>In these higher-stake situations with more sensitive information, any type of &quot;direct&quot; proof is a bit of a terrifying idea, for if something goes wrong between you and who you are interacting with, the consequences can be devastating. We want some way to prove something, without necessarily having to reveal any information about the proof claim. </p>
<h2 id="zero-knowledge-proofs">Zero-Knowledge Proofs</h2>
<p>Think about what we are asking for a second. We want to prove something to someone, without giving any particular facts; we want to endow someone with new information, necesssarily without giving any new information. </p>
<p>These <strong>zero-knowledge proofs (ZKPs)</strong> that validate a claim without imparting new knowledge sounds like an impossible feat. If someone has access to all the information already, and can&#39;t come to the conclusion themself, then how will they ever come to agree with the claim? Remarkably, there are strategies to create such a proof. An example does best here.</p>
<h3 id="the-colorblind-man">The Colorblind Man</h3>
<p>Say your friend is extremely red-green colorblind. You give them two balls, one red and one green. Besides their color, they are completely identical (size, weight, mass distribution, etc.) to each other. To your friend, the balls do in fact look identical (due to the colors), but you want to prove to them they are truly not. Here&#39;s how you do it:</p>
<ol>
<li>Hand them a ball in each hand.</li>
<li>Tell them to put it behind their back and choose to either swap the balls or leave them in the same hands.</li>
<li>Have them reveal to the balls to you and ask if he swapped them or not.</li>
</ol>
<p>You, who&#39;s not colorblind, can answer him no problem. Getting it right once may be a fluke, but the more times you get it right, the more confident your friend should become that there <i>is</i> something differentiating the balls, even if he can&#39;t see it. If you&#39;re friend thinks you&#39;re only guessing randomly, even just getting it right 10 times in a row has probability $(\frac{1}{2})^{10} = 0.00098$, or a less than .1% chance of happening. You can keep repeating the test as long as your friend wants, but soon enough, he&#39;ll have to accept that you aren&#39;t just guessing, but rather seeing something he cannot.</p>
<p>In this, clearly we didn&#39;t change our friend&#39;s perception in anyway—he&#39;s still colorblind. Moreover, we didn&#39;t do any additional tests, like using an RBG monitor to digitally record values for your friend to read. Yet, we were able to convince them with a probabilistic guarantee that he is lacking information, even if we can&#39;t give him that information directly. In essence, nothing was changed of the scenario—no new knowledge was given—yet we were still able to prove to the colorblind friend that he in fact holding two differently colored balls, even if he can&#39;t verify that directly. </p>
<h3 id="inequitable-income">Inequitable Income</h3>
<p>You recently joined a small company—no more than 5 people including yourself—and have recently begun to feel unvalued. You think you might be paid less than average, and you bring this up to the others. They try to explain to you that you are being paid fairly, despite the amount of work you put in. They seem confident enough, but they won&#39;t tell you their salary. How can you prove to them that you are paid less than average, without getting the data from your colleagues?</p>
<p>Let&#39;s say you, as person $A$, have a monthly salary of $ \$ a$, and the other four have salaries of $ \$ b, \$ c, \$ d, \$ e $. Now this is what we do:</p>
<ol>
<li>You give a random, placeholder number $x$.</li>
<li>Then person $B$ computes the sum $x + b$, and tells person $C$ this value.</li>
<li>Person $C$ then adds their own salary to the sum to get $x + b + c$, and tells $D$ this number</li>
<li>People $D$ and $E$ do the same thing, until $E$ tells you the final number $x + b + c + d + e$.</li>
<li>Finally, since you know the value $x$, you can subtract it and recompute the value of $a + b + c + d + e$</li>
<li>You can then announce the average to the group $\large{\frac{a + b + c + d + e}{5}}$</li>
</ol>
<p>Then, without any other individual having to know any other person&#39;s salary, can confidently agree that this is the group average, and enjoy the ensuing chaos of wealth mismanagement. This all works because of the value $x$: no one except you knows the value, so at each step, no other person will have enough information to deduce others&#39; salaries from just their own. So without the need for any specific piece of new information, we are still able to deduce averages from a set of secret numbers.</p>
<hr>
<p>These last two examples, particularly the former with the colorblind man, encapsulates the idea of zero-knowledge proofs. You, and possibly other parties, have secret information you want (or have) to keep secret, and somehow manipulate whatever knowledge you already have to deduce something meaningful. Even after I saw these two examples, it still was a surprising fact to me that not only such an concept exists, but also has super practical applications.</p>
<p>But we haven&#39;t actually specified <em>exactly</em> what makes a zero-knowledge proof, well, zero-knowledge. If we (the <strong>prover</strong>) are trying to prove some statement to a <strong>verifier</strong> with a ZKP, there are 3 properties we&#39;d want to satisfy:</p>
<ol>
<li><strong>Completeness:</strong> if the statement is true, then an honest verifier will be convinced of it by an honest prover<ul>
<li>This ensures we <em>can</em> prove the statement</li>
</ul>
</li>
<li><strong>Soundness:</strong> if the statement is false, then there is no proof that can convince the verifier (up to some small probability)<ul>
<li>This ensures our proof method is trustworthy</li>
</ul>
</li>
<li><strong>Zero-Knowledge:</strong> if the statement is true, then no verifier learns anything <em>except</em> that the statement is true<ul>
<li>This protects our secret</li>
</ul>
</li>
</ol>
<!-- So if we have a secret $x$, and a claim it satisfies $P(x)$, we want to convince the other person of just $P(x)$ without revealing $x$. -->
<p>The first two qualities are that of a general <strong>interactive proof system</strong>, which is a type of proof that relies on a conversation-esque exchange between the prover and verifier (like in the colorblindness example). These interactive proofs follow a <strong>protocol</strong> that dictates the flow of conversation, and in the context of our qualities, someone is honest when they legitimately follow this protocol in good faith.</p>
<p>Let&#39;s do a more practical example. </p>
<h2 id="the-discrete-logarithm-problem">The Discrete Logarithm Problem</h2>
<p>You and your friends set-up your own little secret network to talk to each other privately. To make sure no one else can spy on you guys, you implement a password system: everyone picks a username that consists of 3 numbers, two integers $A$ and $B$ as well as a (usually large) prime $p$. Your password $x$ will be a number such that $B = A^{x} \bmod p$. Obviously, if you wanted to log-in, you could just give your password everytime, but that puts you at risk for eavesdroppers or anyone listening in. Ideally, we want to be able to prove to our network that we do actually know our password, <em>without having to give the password</em>. This way, if anyone wants to break into our account, they would have to brute force it, <a href="https://sebastiaagramunt.medium.com/discrete-logarithm-problem-and-diffie-hellman-key-exchange-821a45202d26">which isn&#39;t the best use of one&#39;s time</a>. </p>
<p>One issue, for example, is that you could have multiple solutions to a modular arithmetic problem. The equation $13 = 3^x \bmod 17$. You can check that $x = 4$ is a solution. But, due to <a href="https://en.wikipedia.org/wiki/Fermat%27s_little_theorem">Fermat&#39;s little theorem</a>, we also know that $1 = 3^{16} \bmod 17$. Then for any integer $k$, we know that </p>
<center>
$3^{4 + 16k} \bmod 17 = 3^4 \cdot (3^{16})^k \bmod 17 = 13 \cdot 1^k \bmod 17 = 13 \bmod 17$
</center>

<p>so even if you have a solution, it doesn&#39;t necessarily mean you found the particular solution that is our password.</p>
<p>Finding $x$ given $A,B,p$ is known as the <strong>discrete logarithm problem</strong>, and due to the difficulty of brute forcing, can actually be used as a method of identification (like a password). An additional thing to note, to maximize the search space for people brute forcing your $x$ value, we choose $A$ to be a <strong>generator</strong>, meaning that for every value $m = 1,2,\cdots,p-1$, there is a value $n$ such that $m = A^{n} \bmod p$. You tell everyone your $A,B,p$, and no one but you ever has to know your $x$. But you can still confidently prove to people that you do know it, and that you are in fact <em>actually you</em>. </p>
<p>After we (the prover) have distributed our values of $A,B,p$ (to any potential verifier) such that $B = A^x \bmod p$, this will be our protocol:</p>
<!-- 1. The prover picks a random number $r$ and calculates the value $C = A^r \bmod p$
2. The verifier now executes one of the following randomly:
  * They ask the prover for the value of $r$
  * They ask the prover for the value of $(x + r)$
3. The verifier now checks they get the expected value.
  * If they asked for $r$, they check that indeed $A^r \bmod p = C$
  * If they asked for $(x + r)$, they check that they get 
<center>
$A^{(x + r)} \bmod p = A^{x} \cdot A^{r} \bmod p = B \cdot C$
</center>
4. Verifier repeats steps 1–3 until they are satisfied.
 -->
<!-- any instance of (x+r) mod (p-1) in other notes is due to the order of the group; g^{x} = g^{x mod p-1} since it is an element that generates the whole group i.e. it is an element of order p-1 -->
<ol>
<li>The prover picks a random number $r$ and calculates the value $C = A^r \bmod p$</li>
<li>The verifier now flips a coin. If the coin is heads they give the prover $c = 0$, and if tails $c=1$.</li>
<li>The prover sends the verifier the value of $cx + r$</li>
<li>The verifier now checks they get the expected value:<center>
$A^{(cx + r)} \bmod p = (A^{x})^c \cdot A^{r} \bmod p = B^c \cdot C$
</center></li>
<li>Verifier repeats steps 1–3 until they are satisfied.</li>
</ol>
<p>We see parts of our previous ZKPs appear here: 1) we let the verifier do a random action to test the prover&#39;s knowledge just like in the colorblind friend example, and 2) we do a pseudo-encryption of our password $x$ by adding a random number $r$ to obscure it in a sum.</p>
<p>Now we want to verify this acutally <em>works</em>, both as a password-method and a zero-knowledge proof.</p>
<p>So say someone was trying to hack into our account. If they knew what our verifier was going to give for $c$, then theoretically they could cheat their way into our account. There are two possibilities they could guess, being the value of $c$: </p>
<ul>
<li>$c=0$. Then the attacker just pick a random value $r$ and the verification process works as normal.</li>
<li>$c=1$. Then the attacker pick a random value $r&#39;$ and instead of giving the value $C$ that the verifier requests, they instead give the value $C{&#39;} = (A^{r{&#39;}} \bmod p) \cdot B^{-1}$. Then when the verifier wants the value $x+r$, the attacker instead gives $r&#39;$, so that 
<center>
$A^{r&#39;} \bmod p = (A^{r&#39;} \bmod p) \cdot B^{-1} \cdot B = C&#39; \cdot B$
</center>
which would be match the swapped values the verifier would expect.</li>
</ul>
<p>But, if the attacker is wrong, because of how difficult it is to compute the discrete logarithm, they would not be able to reverse any of the new values they need with the value of $c$ they did not expect. So someone who doesn&#39;t know the password $x$ would have a 50% chance of passing the test, so the verifier just does this enough times until they are convinced. So at the very least, this does work as an effective identity/password check. So, also, this shows our proof is both <strong>sound</strong> and <strong>complete</strong>: if we don&#39;t, then it&#39;s near impossible for someone to cheat, and if we do know our password, a verifier should be convinced eventually.</p>
<p>This proof is also <strong>zero-knowledge</strong> since, well, we only worked with the public information. You can imagine building a simulator—like a computer—that can mimic exchanges between a prover and verifier (as if following the procedure of an attacker in our proofs of soundness and completeness) that operates entirely on its own. And I don&#39;t know about you, but a computer program is only working with what it&#39;s given, so if this interactive proof works within the confines of a computer, no new information is ever given.</p>
<center>
$\blacksquare$
</center>

<p>While this is a good proof of concept, it does require a lot of work in practice. If you want to try and wrap your head around these types of proofs before moving on, here&#39;s another simple one about <a href="https://decentralizedthoughts.github.io/2020-12-08-a-simple-and-succinct-zero-knowledge-proof/">proving knowledge of a vector</a>. It&#39;s an interactive proof with a focus on succinctness, and I found it to be quite helpful to think about some of the related concepts in cryptography and zero-knowledge proofs. The important concept to take away from this article and our above example with the discrete logarithm, randomness is an extremely useful way to instantly bound the error of our proofs; we don&#39;t need the proof to be 100% confident, we just need it to be confident <em>enough</em> such that the prover can&#39;t cheat if they tried.</p>
<h1 id="non-interactive-zero-knowledge-proofs">Non-Interactive Zero-Knowledge Proofs</h1>
<p>Before, in the example with the discrete logarithm problem and the colorblind man, we had this verifier act as an arbiter: they make a random decision that should prevent hacks (i.e. swapping the balls, sending $c=0$ or $c=1$), and after some arbitrary number of successes, they accept that the prover is genuine. Now imagine that <em>you</em> are the verifier, or are implementing this. Do you really want to sit through doing the <em>same</em> test over and over again, until you feel convinced? Do you really want to have to rely on some random mechanism every time that you carry out? Even if you make a computer to do this for you, imagine how annoying that must be to work with every time you want to log in with a password. Seems like a pain.</p>
<p>What we would ideally use is a <strong>non-interactive</strong> protocol: something that removes our need to have to always make a random choice and carry it out until some subjective level of confidence. But again, we don&#39;t want to compromise on zero-knowledge; we like our privacy. Fortunately, others&#39; have come to the same issues and have come up with <strong>zero-knowledge succinct non-interactive arguments for knowledge (zk-SNARKs)</strong> to solve many of our qualms. To keep it clear, let&#39;s go over exactly what each part of this obscenely long name actually means:</p>
<ul>
<li><em>zero-knowledge</em>: this is the same as before; we leak no new information and only prove that we know a claim is true without divulging anything specific about it.</li>
<li><em>succinct</em>: our proof takes a <strong>constant amount of space</strong>, i.e. the proof takes the same amount of time every time you go through it; we don&#39;t need to do the protocol until we are (subjectively) confident as we did with the previous proofs.</li>
<li><em>non-interactive</em>: our verifier doesn&#39;t give any intermediate input, i.e. no need to decide swapping balls or picking $c=0$ or $c=1$.</li>
</ul>
<p>So here&#39;s a super simple zk-SNARK:</p>
<hr>
<p><strong>Claim:</strong> I want to prove to my friend that two entrances to a building are connected.</p>
<p><strong>Proof:</strong> All I need to do is have my friend watch from outside that I can in fact enter the one door and exit the other. </p>
<ul>
<li>This is zero-knowledge since all my friend gets is knowledge that my claim was true and nothing more; they don&#39;t actually get to see how they are connected or anything more about the buliding. </li>
<li>It&#39;s succinct since I only need to do it once, since there is no room for doubt once I&#39;ve shown it once (how do you prove something like this by a fluke?). </li>
<li>Finally, it&#39;s non-interactive since my friend doesn&#39;t need to actually do anything but observe.</li>
</ul>
<hr>
<p>That&#39;s the idea of zk-SNARK, at least. We&#39;ll build up to a pretty surprising zk-SNARK by the end of this, but to get there, we&#39;ll have to cover some more ground.</p>
<p>Now the remainder of this post will be pretty mathematically heavy in the worst way possible. The ideas are important and useful, and the overarching concept of a zero-knowledge proof is extremely interesting, but the mechanics behind them are fairly tedious—and that&#39;s just how it goes sometimes with cryptography. To ensure security, often times the best (and first thought about) ideas are to obscure the data with as many impossibly hard operations to undo. The notation might get dense, but hopefully we build up to it in a comprehensible manner.</p>
<h2 id="honesty-checks">Honesty Checks</h2>
<p>Our discrete logarithm example, while not only gave us a nice demonstration of zero-knowledge proofs, they also now have given us an additional encryption method. The entire problem hinged on the fact that calculating discrete logarithms <strong>are hard</strong> to begin with. So we can use exponents, actually, to hide and encrypt lots of other pieces of data. And moreoever, can act as a safeguard to make sure no one is cheating us.</p>
<!-- For example, say we're working with some protocol where the verifier is testing our knowledge of something, say, a polynomial. One way to do that, is by picking a random number, and having us plug that into our polynomial, and giving it back to them. So let's say they pick a random number $s$, they can force us (the prover) to use $s$ by exponentiating it and picking an additional **encryption shift** $\alpha$. Then -->
<p>For example, say we&#39;re a verifier, and want to make sure that our prover follows the protocol of multiplying a number we give them. They can multiply whatever they want, but they have to multiply the number we give them. We can force this with exponents because the discrete logarithm is hard. </p>
<ol>
<li>The verifier picks a generator $g$ (like from the discrete logarithm), our secret number $s$, and our <strong>encrypted shift</strong> $\alpha$.</li>
<li>the verifier gives the prover the values $g^s$ and $g^{\alpha \cdot s}$.</li>
<li>The prover with some number $c$, then gives back the values $(g^s)^c = g^{cs}$ and $(g^{\alpha \cdot s})^c = g^{c\alpha s}$.</li>
<li>The verifier checks that $(g^{cs})^\alpha = g^{c\alpha s}$.</li>
</ol>
<p>Because of how hard it is to cheat this system by finding another exponent to get equal values that the verifier would expect, the prover is forced to use the encrypted value of $g^s$, and the shift of $g^{\alpha \cdot s}$ gives us insurance to check the prover&#39;s honesty at the end. And in the same way the prover doesn&#39;t learn the values of $s$ or $\alpha$, we don&#39;t learn the value of $c$ they want to multiply by. We only checked that they were honest.</p>
<h2 id="polynomial-knowledge">Polynomial Knowledge</h2>
<p>Now the reason why that&#39;s important, is that exponents give us all the methods we need to check more complicated values, like that of <strong>polynomials</strong>. The question we&#39;ll aim to answer is:</p>
<center>
<strong>Can we prove to a verifier we know a polynomial $p(x)$ of degree $d$ has roots at $r_1, r_2, \cdots, r_n$ without revealing our polynomial?</strong>
</center>

<p>In other words, can we prove to a verifier that for some polynomial $h(x)$, we know that $p(x) = (x-r_1)(x-r_2)\cdots (x-r_n)\cdot h(x)$? For brevity and convenience, we&#39;ll call the <strong>target polynomial</strong> $t(x) = (x-r_1)(x-r_2)\cdots (x-r_n)$.</p>
<hr>
<p>The reason why polynomials are interesting is because they are incredibly hard to cheat. Say the prover has a polynomial $f(x)$, and claims to know the <em>exact</em> polynomial that the verifier has $g(x)$, that is the prover claims $f(x) \equiv g(x)$. If both polynomials are of degree $d$, then either $f(x)=g(x)$ has at most $d$ solutions by the Fundamental Theorem of Algebra, or has infinite solutions if and only if $f(x) \equiv g(x)$. So if the verifier picks a random value $s$ for the prover to evaluate, it is extremely unlikely that $f(s) = g(s)$ if they are not genuinely the same. If the prover does not know $g(x)$ and just guessed a random polynomial $f(x)$, if the verifier pick a random integer from the range $s \in [1,10000]$, there is <em>at most</em> a $\frac{d}{10000}$ chance that $f(s) = g(s)$.</p>
<hr>
<h3 id="first-attempt">First Attempt</h3>
<p>Here&#39;s a naive way to prove to a verifier they know such a polynomial:</p>
<p><strong>Protocol Attempt 1:</strong></p>
<ol>
<li>The verifier picks a random number $s$ and gives this to the prover along with $t(s)$.</li>
<li>The prover calculates $h(s) = \frac{p(s)}{t(s)}$ and passes that along to the verifier with $p(s)$.</li>
<li>The verifier checks that $h(s) \cdot t(s) = p(s)$.</li>
</ol>
<!-- The idea is that polynomials can only share a finite number of points if they are not identical. That's because for two polynomials $f(x),g(x)$ of degree $d$, $f(x) = g(x)$ must either have less than $d$ solutions or infinite solutions. That's because $f(x)-g(x)$ is at most a polynomial of degree $d$, and by the Fundamental Theorem of Algebra, $f(x)-g(x) = 0$ can have at most $d$ solutions, unless $f(x) \equiv g(x)$. So if our prover does not have a polynomial  -->
<p>This, though, has the issues of:</p>
<ul>
<li>The prover can just pick an arbitrary number $h$ and calculate $p = h \cdot t(s)$ and that will satisfy the verifier.</li>
<li>Since we give the prover access to the number $s$, the prover can just make a new polynomial that happens to have the value of $p(s) = t(s) \cdot h$.</li>
<li>There&#39;s no verification of the degree of the polynomial.</li>
</ul>
<p>The first two issues are purely because we don&#39;t encrypt anything; we just give the values of $s$ and $t(s)$. We need a way to obscure them so that computations with them are still feasible, but the prover can&#39;t use them to cheat the protocol. </p>
<h3 id="homomorphic-encryption">Homomorphic Encryption</h3>
<p>The way we can do this is in line with our honesty checks and the discrete logarithm, and exploiting the properties of exponents. Say our polynomial was a quadratic $f(x) = x^2 - 3x + 2$. We can encrypt $f(x)$ the same way we have been doing before by using a generator $g$ taken modulo $n$ (ideally a prime):</p>
<center>
$g^{f(x)} \bmod n = g^{x^2 - 3x + 2} \bmod n = (g^{x^2})^1 \cdot (g^x)^{-3} \cdot (g^0)^2 \bmod n$
</center>

<p>This type of encryption is known as <strong>homomorphic encryption</strong>, as our encryption method has a nice structure to it that allows us to do our arithmetic operations on them without having to decrypt it. In particular, if we let $E(s) = g^s \bmod n$ be our encryption as we have been, the structure we get is that $E(n + m) = E(n) \cdot E(m)$ by exponent rules.</p>
<hr>
<p>One issue, though, is that we <em>cannot</em> multiply two encrypted values together with this homomorphic encryption scheme. If you have two numbers $a,b$ that have been encrypted as $E(a) = g^a$ and $E(b) = g^b$, we can easily find $E(a + b) = E(a)E(b)$ as we stated above. But only given $E(a), E(b)$, you cannot find an expression for $E(ab)$. Similarly, we also can&#39;t find an expression for $E(a^b)$. We&#39;ll address this later.</p>
<hr>
<p>As we&#39;ve discussed, reverse engineering an exponent modulo a number is especially hard because of how the modulo operation cycles, leaving room for many options to satisfy the equation and thus making finding a specific solution hard. So we can update our protocol:</p>
<p><strong>Protocol Attempt 2:</strong></p>
<ol>
<li>The verifier picks a random number $s$, and sends encrypted powers of $s$ to the prover $\{g^{s^0}, g^{s^1}, g^{s^2}, \cdots, g^{s^d}\}$.</li>
<li>The prover calculates $h(x) = \frac{p(x)}{t(x)}$. With the encrypted values, they calculate and send to the verifier $g^{p(s)}$ and $g^{h(s)}$.<ul>
<li>i.e. $g^{p(s)} = g^{c_d s^d + \cdots c_1 s^1 + c_0 s^0} = (g^{s^d})^{c_d} \cdots (g^{s^1})^{c_1} \cdot (g^{s^0})^{c_0}$ for the coefficients $c_d, \cdots, c_0$</li>
</ul>
</li>
<li>The verifier checks that $g^{p(s)} = (g^{h(s)})^{t(s)} = g^{h(s) \cdot t(s)}$.</li>
</ol>
<p>Although I&#39;ve left it out for convenience, remember that all these encrypted values $g^x$ are taken to mean $g^x \bmod n$. It&#39;s the discrete logarithm that is difficult, not the normal logarithm.</p>
<p>So by encrypting $s$ and just not giving the value of $t(s)$, we&#39;ve fixed our issues, right? </p>
<hr>
<p>The first two are in fact fixed, but we still need a way to enforce the degree requirement. In a way, we already do have a type of restriction since the verifier only gives the prover powers of $s$ encrypted with $\{g^{s^0}, g^{s^1}, g^{s^2}, \cdots, g^{s^d}\}$. But this restriction is only in place if the prover uses these and only these values. There&#39;s nothing stopping the prover from just not using those encrypted values of $s$, and using their own constructed numbers to cheat. Here&#39;s a more concrete way of seeing this:</p>
<p>What the verifier wants at the end of the day is for the equation $g^{p(s)} = (g^{h(s)})^{t(s)}$ to hold, and is trusting that $g^{p(s)}$ and $g^{h(s)}$ are provided truthfully by the prover. But if we have a prover that <em>does not know</em> a polynomial, all they need to do to fool the verifier is to give values $z_p = g^{p(s)}$ and $z_h = g^{h(s)}$. In other words, the prover just needs to find a solution to $z_p = (z_h)^{t(s)}$. Which, unfortunately for our protocol, is quite easy.</p>
<ul>
<li>Let $z_h = g^r$ for some chosen random $r$ </li>
<li>Then we just need $z_p = (g^r)^{t(s)} = (g^{t(s)})^r$</li>
<li>Since the target polynomial $t(x)$ is public, the prover can solve $g^{t(s)}$ with the given values $\{g^{s^0}, g^{s^1}, g^{s^2}, \cdots, g^{s^d}\}$</li>
<li>So finding $z_p$ is done</li>
</ul>
<p>So finding a solution is no harder than essentially picking a random number. We want some way to ensure that the prover uses and only uses the values the verifier gives them from $\{g^{s^0}, g^{s^1}, g^{s^2}, \cdots, g^{s^d}\}$ in finding their $z_p,z_h$. If we can do that, the only way they&#39;ll be able to calculate $z_p,z_h$ is probably with a polynomial they have.</p>
<hr>
<p>Readily enough, we have done this with our honesty checks above: we provide some arbitrary shift $\alpha$ only the verifier knows, to make sure the prover didn&#39;t leave anything out or cheat.</p>
<p><strong>Protocol Attempt 3:</strong></p>
<ol>
<li>The verifier picks random number $s$ and $\alpha$. They send the encrypted powers of $s$ and the shifts to the prover: $\{g^{s^0}, g^{s^1}, g^{s^2}, \cdots, g^{s^d}\}$ and $\{g^{\alpha s^0}, g^{\alpha s^1}, g^{\alpha s^2}, \cdots, g^{\alpha s^d}\}$.</li>
<li>The prover calculates $h(x) = \frac{p(x)}{t(x)}$. With the encrypted values, they calculate and send to the verifier $g^{p(s)}$, $g^{\alpha p(s)}$, and $g^{h(s)}$.</li>
<li>The verifier checks that $g^{p(s)} = (g^{h(s)})^{t(s)} = g^{h(s) \cdot t(s)}$, and that $(g^{p(s)})^\alpha = g^{\alpha p(s)}$.</li>
</ol>
<p>The first check the verifier does is to see the values match like before, and the second check is to make sure there was no cheating and only the encrypted values of $s$ were used; the prover had to give a polynomial of degree $d$ and had to evaluate it at the $s$ the verifier gives them, as that is the only way to preserve the $\alpha$ shift. </p>
<p>For example, if the prover claimed they knew a quadratic with $d=2$, they claim they have a polynomial looking like $p(x)=c_2x^2+c_1x^1 + c_0$. But if they were really trying to sneak in that they had a cubic or quartic or any polynomial of degree higher than 2, they would not be able to calculate the terms needing $x^3$ or $x^4$ since the encrypted and shifted values could not be calculated and thus preserved. But that is only true if the prover used values from $\{g^{s^0},g^{s^1},g^{s^2}\}$. Now by using the $\alpha$ shift, the prover has no choice but to use these values since any deviation from them will appear comparing to the $\alpha$ values.</p>
<p>Further, we can do more than just ensure the degree of the polynomial we&#39;re checking, but also which <em>specific powers</em> are used in the polynomial. If, say, the polynomial was claimed to be a cubic, but only used powers $x^3$ and $x^1$, the verifier can choose to only send in the encrypted and shifted values of $s^3$ and $s^1$. If the prover needed the other powers to evaluate their polynomial, they would be stuck since they can only evaluate the terms with power 3 and 1.</p>
<h3 id="making-it-zero-knowledge">Making It Zero-Knowledge</h3>
<p>So far, our protocol has gone under a few iterations—and to be fair it&#39;s actually pretty robust. But we kind of forgot about making it <em>zero-knowledge</em>. I mean, yes we&#39;ve encrypted the data to prevent any cheating from the prover, but the verifier can theoretically use the values the prover gives to brute force their way to finding the polynomial since they are the ones that generate the secret values $s$ and $\alpha$ from the beginning. For example, ideally our protocol should be secure for even a 1-degree polynomial, and even brute forcing that is just a matter of iterating through a series of numbers.</p>
<p>This is easily enough done in the same way that we&#39;ve been doing before: we have the prover introduce a random parameter $\delta$ that obscures the data. </p>
<p><strong>Zero-Knowledge Protocol:</strong></p>
<ol>
<li>The verifier picks random number $s$ and $\alpha$. They send the encrypted powers of $s$ and the shifts to the prover: $\{g^{s^0}, g^{s^1}, g^{s^2}, \cdots, g^{s^d}\}$ and $\{g^{\alpha s^0}, g^{\alpha s^1}, g^{\alpha s^2}, \cdots, g^{\alpha s^d}\}$.</li>
<li>The prover calculates $h(x) = \frac{p(x)}{t(x)}$. With the encrypted values, they calculate $g^{p(s)}$, $g^{\alpha p(s)}$, and $g^{h(s)}$. With a random number $\delta$, they send the verifier $(g^{p(s)})^\delta$, $(g^{\alpha p(s)})^\delta$, and $(g^{h(s)})^\delta$</li>
<li>The verifier checks that $(g^{p(s)})^\delta = ((g^{h(s)})^\delta)^{t(s)} = g^{\delta \cdot h(s) \cdot t(s)}$, and that $((g^{p(s)})^\delta)^\alpha = (g^{\alpha p(s)})^\delta$.</li>
</ol>
<h3 id="making-it-non-interactive">Making it Non-Interactive</h3>
<p>Our protocol is very similar to our discrete logarithm problem. I mean, we based it off of what we did there, only generalizing what we did with polynomials instead of specific numbers. So this doesn&#39;t really show us anything we haven&#39;t already seen before. We want to try and make it non-interactive so our verifier doesn&#39;t have to constantly monitor our verification. And more importantly, so our protocol is <em>trustworthy</em>: due to the nature of the interactive parts, verifiers could collude with provers, making each protocol use a one-time check. Even better would be if we could make it also succinct, and have each call of the protocol takes a consistent amount of time. </p>
<p>One way we can remove the need for interactivity is by, well, replacing the interactive parts with some constant, reliable parameters to always use as oppose to the ones suggested by the verifier. In this case, the verifier has to pick a value $t(s_0)$ (since the target polynomial $t(x)$ is known, really we just need to fix an $s_0$) as well as a fixed shift $\alpha_0$. But we need these to be trustworthy, and unable to be leaked.</p>
<p>We could just try encrypting these values like before by exponenitating modulo $n$ like before with $g^{t(s_0)}$ and $g^{\alpha_0}$. But the problem is, we&#39;ve also encrypted the other values like $p(s_0)$ and $h(s_0)$, and as we said, we can&#39;t multiply two encrypted values together, which is exactly what the checks the verifier needs at the end of the protocol; with our encryption, if we have $E(\alpha_0)$ and $E(p(s_0))$, we have no way of getting $E(\alpha_0 p(s_0))$.</p>
<p>There&#39;s one extra piece of machinery we&#39;ll need: <strong>elliptic curves</strong>. Elliptic curves are a class of implicit functions of the form $y^2 = x^3 + ax + b$ and their relation to the whole of cryptography is a bit too wide to encapsulate in this post, so perhaps we&#39;ll come back to them another day. The important thing about them though is that we can establish <strong>cryptographic pairings</strong> with these curves that can get around our multiplication issue.</p>
<p>A <strong>cryptographic pairing</strong> is a function $e(\cdot, \cdot)$ that take two encrypted numbers, and outputs the product of those two numbers in a different representation (i.e. outputs the product of the numbers encrypted in a new way). Because the output space is a different &quot;encryption scheme&quot; from before, it makes it irreversible, and a &quot;one-time operation&quot;; you can&#39;t use the output of $e(\cdot, \cdot)$ in another cryptographic pairing in a meaningful way. The key properties of this pairing are:</p>
<center>
$e(g^a, g^b) = e(g^b, g^a) = e(g^{ab}, g^1) = e(g^a, g^1)^b = e(g^1, g^b)^a = e(g^1,g^1)^{ab}$
</center>

<p>I know this is a <em>very rough</em> sketch as to how we are overcoming the problem of multiplying encrypted values, but for the sake of brevity, we&#39;ll come back to it sometime later (if you can&#39;t wait, <a href="https://eprint.iacr.org/2004/064.pdf">check this out</a>). The important idea to keep in mind is that we have a way of multiplying encrypted values of $t(s)$ and $\alpha$ in a useable way.</p>
<p>So now, to make our proof non-interactive, we fix our values $\alpha, t(s)$, and then encrypt them $g^\alpha, g^{t(s)}$. These values will be the ones used by every prover and verifier moving forward, and to carry out our operations, we will use our cryptographic pairing function, which we&#39;ll see below.</p>
<hr>
<p>Also, as an aside, we no longer need multiplicative group generators like we have used before. $g^n$ can now mean adding the <em>generator of the elliptic curve</em> $g$ to itself $n$ times. It&#39;s essentially the same (and acts the same for our purposes), but removes an extra component from our process.</p>
<h3 id="the-final-protocol">The Final Protocol</h3>
<p>We are now ready to put together our final protocol for knowledge of a polynomial of degree $d$ with the same roots as $t(x)$. The keys below are the necessary elements each party needs on their side of the proof beforehand. </p>
<!-- As before, encrypted values $g^x$ are taken to mean $g^x \bmod n$. -->
<p><strong>Set-Up:</strong></p>
<ul>
<li>Fix random values $s$ and $\alpha$</li>
<li>Establish a cryptographic pairing $e(\cdot,\cdot)$ and a generator $g$</li>
<li>Find encryptions $g^\alpha$, $\{g^{s^0}, g^{s^1}, g^{s^2}, \cdots, g^{s^d}\}$, $\{g^{\alpha s^0}, g^{\alpha s^1}, g^{\alpha s^2}, \cdots, g^{\alpha s^d}\}$ </li>
</ul>
<p>Now we distribute to the prover and verifier their respective information they are allowed to work with:</p>
<ul>
<li>Proof key: $\left(\{g^{s^0}, g^{s^1}, g^{s^2}, \cdots, g^{s^d}\}, \{g^{\alpha s^0}, g^{\alpha s^1}, g^{\alpha s^2}, \cdots, g^{\alpha s^d}\}\right)$</li>
<li>Verification key: $(g^\alpha, g^{t(s)})$</li>
</ul>
<p><strong>Proof:</strong></p>
<ul>
<li>Wants to prove knowledge of $p(x) = t(x) \cdot h(x) = c_d x^d + \cdots + c_0 x^0$</li>
<li>Let $h(x) = \frac{p(x)}{t(x)}$</li>
<li>Calculate $g^{p(s)}, g^{h(s)}$ using $\{g^{s^0}, g^{s^1}, g^{s^2}, \cdots, g^{s^d}\}$</li>
<li>Calculate $g^{\alpha p(s)}$ using shifted values $\{g^{\alpha s^0}, g^{\alpha s^1}, g^{\alpha s^2}, \cdots, g^{\alpha s^d}\}$</li>
<li>Pick a random shift $\delta$</li>
<li>Send to the verifier our proof $\pi = \left(g^{\delta p(s)}, g^{\delta h(s)}, g^{\delta \alpha p(s)} \right)$</li>
</ul>
<p><strong>Verification:</strong></p>
<ul>
<li>With $\pi = \left(g^{\delta p(s)}, g^{\delta h(s)}, g^{\delta \alpha p(s)} \right)$, we do our two checks for satisfiability and degree of the polynomial</li>
<li>Does the polynomial work? Check that $e(g^{\delta p(s)}, g) = e(g^{t(s)}, g^{\delta h(s)})$</li>
<li>Did the prover cheat? Check that $e(g^{\delta \alpha p(s)}, g) = e(g^{\alpha}, g^{\delta p(s)})$</li>
</ul>
<p>And that&#39;s our protocol from start to finish. Without ever needing to reveal what $p(x)$, we can confirm with high probability that our prover&#39;s polynomial has the desired roots matching $t(x)$. We can add other requirements to the polynomial, like only including certain powers as we discussed, or others such as it must be a square polynomial.</p>
<h1 id="general-zk-snarks">General zk-SNARKs</h1>
<p>So far, we&#39;ve spent roughly 6000 words talking about polynomials and homomorphic encryption, and that&#39;s with skipping explanations of elliptic curve cryptography thrown in there too. But in practice, when was the last time you saw someone work with a polynomial directly? If I had to think of when someone would want to prove knowledge of something in practice, it would probably be something less direct, like knowing the output of a program, or a secret input (like a password). Those don&#39;t seem related to polynomials at all. For example, if I had a computer program and a given output, I&#39;d like to show I have the corresponding input without revealing that input.</p>
<p>But of course, in the weirdest ways, polynomials are the current backbone of zk-SNARKs. And unfortunately, like with elliptic curves from before, require an already huge amount of literature to even crack the surface of how they work. Ultimately, the idea is that given any program, we can make the problem of proving knowledge-of-input into a question of knowledge-of-polynomial. Here are the rough steps (as outlined in this more in-depth <a href="https://medium.com/@VitalikButerin/quadratic-arithmetic-programs-from-zero-to-hero-f6d558cea649">post</a>):</p>
<ol>
<li><strong>Computation:</strong> The actual code for the program itself.</li>
<li><strong>Flattening:</strong> We turn the code into a combination involving expression only involving $=+,-,\times,\div$. These arithmetic operations essentially correspond to different types of gates in a circuit. This is probably the hardest, least obvious step, and even now it is not clear to me what are the restrictions for programs that can be converted to these <em>arithmetic circuits</em>. I&#39;d recommend reading <a href="https://people.cs.georgetown.edu/jthaler/firstcircuitlecture.pdf">this</a>.</li>
<li><strong>R1CS:</strong> With the arithmetic circuit, we now convert it to a <em>rank-1 constraint system</em>. An R1CS is a set of groups of 3 vectors $(a,b,c)$, that has a solution $x$ such that $(a \cdot x) \times (b\cdot x) = c\cdot x$ where $\cdot$ is the standard dot product. Each group of these 3 vectors $(a,b,c)$ represents some kind of constraint on our solution. In our case, we will have a triple of vectors $(a,b,c)$ for each gate/operation we have in our arithmetic circuit. So if our arithmetic circuit has 4 steps in it, we&#39;ll have 4 triplets of vectors constraining our solution $x$ that it must all satisfy. The length of the vectors will be equivalent to the number of variables needed in the circuit. Here&#39;s an example conversion of <a href="https://crypto.stackexchange.com/questions/55963/converting-to-rank-one-constraint-system-r1cs">an arithmetic gate to R1CS constraint vectors</a>. </li>
<li><strong>QAP:</strong> We do yet another conversion from R1CS to a <em>quadratic arithmetic program</em>. The idea is to encode our vector constraints in polynomials. If, for example, we had 5 constraints with vectors of length 7, we would have 5 pairs of $(a,b,c)$ constraints where $a,b,c$ are all length 7 vectors. Then, we could encode these in 3 groups of 7 polynomials (in this case, they would be of degree $5-1=4$). Each polynomial represents a coordinate in the vector, and each group represents whether that vector is the $a$, $b$, or $c$ vector in the constraint. Since we have 5 constraints, we then retrieve our each constraint vector by plugging in $x=1,2,3,4,5$ to each polynomial and read off the values by group and coordinate. We can create these polynomials via <a href="https://en.wikipedia.org/wiki/Lagrange_polynomial">Lagrange interpolation</a>, or your favorite way to fit polynomials to specific values. This is why the degree of the polynomials are 1 less than the number of constraints: you need exactly $d+1$ points to determine a polynomial of degree $d$.</li>
</ol>
<p>The point of putting our program into a QAP is that we can now do our R1CS verification a lot more compactly. Instead of checking all the dot products individually between our solution vector $x$ and the constraint vectors, we can dot product the solution once with our polynomials. Dot products are just combinations of addition and multiplication, so the result of $(x \cdot A(t)) \times (x \cdot B(t)) - x\cdot C(t) = F(t)$ will just be another polynomial in $t$. Our solution vector is genuine if $F(t) = 0$ for $t=1,2,3,4,5$ in our above example, since plugging in those values corresponds to checking a different R1CS constraint (that represents one of our arithmetic logic gates).</p>
<p>But now, we&#39;re mostly at the point in which our zk-SNARK protocol for polynomials is starting to look like a more useable tool for general programs. There are a few additional steps outlined in some of the links above, but the core idea is here, of encoding the computation of the program in a polynomial that we later can check the knowledge of via a zk-SNARK.</p>
<h1 id="conclusion">Conclusion</h1>
<p>There are a lot of uses that zero-knowledge proofs can find themselves in. Basically, whenever you want any level of privacy. From passwords, to graphs, to polynomials, or to <a href="https://www.nature.com/articles/ncomms12890">nuclear disarmament</a>. And its most popular use, blockchains and cryptocurrencies (good way of checking valid transactions without needing to reveal people&#39;s currency balances). The underlying theory of zero-knowledge proofs, though, is simultaneously easy to understand, and difficult to implement. The theory is rich, but dense, so pehaps one of these days we&#39;ll fill in the gaps of elliptic curves (which definitely deserves its own post) and fully fleshing out how we can convert computer programs to polynomials.</p>
<p>For more reading and types of proofs, here&#39;s a nice simple example for proving knowledge of coloring a graph that can be found <a href="https://resources.mpi-inf.mpg.de/departments/d1/teaching/ss13/gitcs/lecture9.pdf">here</a> or <a href="https://www.cs.cmu.edu/~goyal/s18/15503/scribe_notes/lecture23.pdf">here</a> (and a nice little <a href="https://web.mit.edu/~ezyang/Public/graph/svg.html#:~:text=Zero%2Dknowledge%20proofs%20permit%20you,the%20game%20as%20a%20verifier.">demo to go with it</a>). Interestingly, as an aside, we can since reduce any NP problem to the 3-coloring problem, this actually gives us a way of generating zero-knowledge proofs for any NP hard problem.</p>
<p>For even more details on zk-SNARKs and zero-knowledge ideas on the whole, see <a href="https://arxiv.org/pdf/1906.07221.pdf%EF%BC%9B#:~:text=Zero%2Dknowledge%20succinct%20non%2Dinteractive,useful%20in%20the%20first%20place%3F">this article</a> that informed much of this post.</p>
]]></description>
         <link>http://xperimex.github.io/blog/zero-knowledge</link>
         <guid isPermaLink="true">http://xperimex.github.io/blog/zero-knowledge</guid>
         <dc:creator><![CDATA[Adi Mittal]]></dc:creator>
      </item>
      <item>
         <title><![CDATA[e, π, and Irrational Numbers]]></title>
         <description><![CDATA[A classic fact and its 10000 word Wikipedia spiral. 

 <p>Irrational numbers are a bit strange to think about. In the sense, they were the first &quot;new&quot; type of number to really challenge early and young mathematicians. We have the natural numbers $\mathbb{N}$ like $\{0,1,2,3,\cdots\}$. From there, we then include the negative numbers $\{ \cdots,-2,-1,0,1,2,\cdots \}$ to have the integers $\mathbb{Z}$, that can be used to represent absences of quantities and additive inverses. From there, we can consider the in-between quantities of fractions, also known as the rationals $\mathbb{Q}$. For a while, this is what we thought all there was to numbers. Pythagoras and the Ancient Greeks famously thought there was no number that wasn&#39;t rational. They had this notion of increasing inclusion of numbers $\mathbb{N} \subset \mathbb{Z} \subset \mathbb{Q}$, and that was the upper limit.</p>
<p>As we now know, this clearly isn&#39;t the case. We&#39;ve talked about irrational numbers a little bit before, specifically on how <a href="http://xperimex.com/blog/constructive-proofs/">$\sqrt{2}$ is irrational</a>. It might be worthwhile going over the proof again:</p>
<p><strong>Claim: $\sqrt{2}$ is irrational.</strong></p>
<p><strong>Proof:</strong> Suppose that $\sqrt{2}$ is not irrational. Therefore it is rational, and can be written as $\sqrt{2} = \frac{p}{q}$ where $p$ and $q$ are distinct coprime numbers (i.e. they don&#39;t share any factors in common; this is a way of sayiing that there is a unique way of writing $\sqrt{2}$ as a fraction in <em>lowest terms</em>). Squaring both sides and moving terms around, this equation becomes $2q^2 = p^2$. Therefore, $p^2$ is even, since it will always have a factor of 2 according to the lefthand-side of the equation. If $p^2$ is even, then $p$ is also even (if you&#39;re unsure of this fact, try some test cases and proving it!). Since $p$ is even, then let&#39;s rewrite it as $p=2n$. Plugging this into our equation yields: $2q^2 = p^2 = (2n)^2 = 4n^2$. Dividing both sides by 2 gives us $q^2 = 2n^2$. Similar to before, the equation implies that $q^2$ and hence $q$ is even due to that factor of 2 on the righthand-side. But this is a contradiction! $p$ and $q$ cannot simultaneously both be coprime and even (share a factor of 2). Hence, our initial assumption that the $\sqrt{2}$ is rational is wrong, and allows us to conclude that $\sqrt{2}$ is irrational. $\blacksquare$</p>
<p>This proof is pretty well-known, but to me, it&#39;s not necessarily obvious. Sure, in retrospect after knowing the proof, it might seem like a good direction to go in and get a contradiction within that rational assumption. But even then, it&#39;s a pretty clever proof. </p>
<p>I mention this, since I was recently thinking about an arguably more famous irrational number: $\pi$. A number studied forever that manages to appear in random sums, integrals, and expressions it has no right being in, it&#39;s no surprise it is one of the few symbols of math that transcends pop culture. And despite that, before writing this, I couldn&#39;t explain or prove why it is irrational. $\pi$ is geometric at heart, and translating to number-theoretic contexts just didn&#39;t seem to make sense. But along the way of finding out its proof (that stumped many before me), there is much to unpack about not just about $\pi$, but irrational numbers on the whole.</p>
<p>If you care for only the proof that $e$ and $\pi$ are irrational, skip <a href="#the-original-proof-of-the-irrationality-of">here</a>. Otherwise, follow through the table of contents for whatever you&#39;re looking for.</p>
<h2 id="decimal-expansions">Decimal Expansions</h2>
<p>The existence of irrational numbers actually implies a lot. For one, there are infinitely many more irrational numbers than rationals. With the classic diagonal argument, we can see that there are not any &quot;more&quot; rationals than integers or naturals. The irrationals are what make the real numbers uncountable. A way we can see that is through decimal expansions: all irrational numbers have non-repeating decimal expansions. So now if you imagine constructing a random number $0.142346\dots$ by picking a random number 0–9 at each digit, the chance of landing a repeating decimal is extremely unlikely.</p>
<p><strong>Claim:</strong> A number is rational if and only if it has a terminating or repeating decimal expansion.</p>
<p><strong>Proof:</strong> $(\Rightarrow)$ The easiest way to see this is through long division. If we have a rational number $\frac{p}{q}$ with $q \neq 0$, then at every step in the long division, we have $q$ possible remainders (being $0,1,2,\cdots,q-1$). If the remainder is 0 at any point, then we are done with the divison algorithm and the decimal expansion terminates (this it the case of 0 being the repeating portion of the decimal). If the remainder is never 0, after $q+1$ steps in the division algorithm, we will get a remainder we have already seen before, and so the division algorithm will keep producing the same digits in order we have seen before from that remainder. Hence the decimal expansion repeats. </p>
<p>$(\Leftarrow)$ Say we have a number $x = a.d_{1}d_{2}\cdots d_{n} \overline{d_{n+1} \cdots d_{n+m}}$ that has integer part $a$, $n$ pre-repeating decimals (each $d_i$ is a digit of the number), and $m$ repeating decimals (indicated by the overline). Then we can left-shift the non-repeating number by multiplying by a power of 10:</p>
<center>

$10^n x = 10^n a + d_{1}d_{2}\cdots d_{n}.\overline{d_{n+1} \cdots d_{n+m}}  \ \ \ \ (1)$

</center>

<p>Since the decimals repeat after an additional $m$ digits, we can shift it further to get another similar looking number:</p>
<center>

$10^{n + m} x = 10^{n + m} a + d_{1}d_{2}\cdots d_{n}d_{n+1} \cdots d_{n+m}.\overline{d_{n+1} \cdots d_{n+m}}  \ \ \ \ (2)$

</center>

<p>Now we can subtract equation $(1)$ from $(2)$ to eliminate the repeating decimal portion:</p>
<center>

$10^{n + m} x - 10^n x = (10^{n + m} a + d_{1}d_{2}\cdots d_{n}d_{n+1} \cdots d_{n+m}) - (10^n a + d_{1}d_{2}\cdots d_{n})$

</center>

<p>Now, see that since we have removed the decimal/fractional part of the numbers in that subtraction, the righthand side of the equation is an integer, call it $N$. Then we can solve for $x$ and see that</p>
<center>

$x = \large{\frac{N}{10^{n+m} - 10^n}}$ $=$ $\large{\frac{N}{(10^m - 1)10^n}}$

</center>

<p>is a quotient of two integers, and so rational.</p>
<center> $\blacksquare$ </center>



<p>So if we want to use real numbers with decimals as we normally do, we need our non-repeating decimals to correspond to something. These are our of course our irrationals. But let&#39;s be clear exactly what non-repeating means. It&#39;s frequently unjustifiably said that since $\pi$ is irrational, it contains every single string of numbers ever conceived, and hence contains exactly the time and date you were born, you will die, and a copy of every book ever written. This is <strong>unknown</strong>. Just consider the non-repeating decimal that only contains 0s and 1s</p>
<center>

$0.10110111011110\cdots \overset{\textrm{n ones}}{111\cdots 1} 0 \overset{\textrm{n+1 ones}}{111\cdots 1}0\cdots$

</center>

<p>Clearly this does not repeat, but certainly also does not contain all possible strings of numbers; it does not even contain all strings of 0s and 1s.</p>
<p>In a sense, too, the irrationals are also necessary for us. Without the irrational numbers, obviously we do not have all the real numbers, but the irrationals are necessary to fill in the gaps and holes left by the rationals to make the real numbers $\mathbb{R}$ as useful as they are. For example, a key property of the reals is that every subset of the reals that has an upper bound, in fact has a <strong>least upper bound</strong>. That is, for a subset $A \subset \mathbb{R}$ such that $\exists x \in \mathbb{R} \ \forall a \in A \ a \leq x$ (i.e. $x$ is an upper bound), there exists $\ell \in \mathbb{R}$ that is less than or equal to all possible upper bounds $x$. The rationals don&#39;t have this property: $\{ x \in \mathbb{Q} \ | \ x^2 &lt; 2 \}$ has upper bounds in $\mathbb{Q}$, but not a least upper bound; we need irrationals and $\sqrt{2} \in \mathbb{R}$ to do this.</p>
<h2 id="completeness-and-the-variety-of-irrationals">Completeness and the Variety of Irrationals</h2>
<!-- continued fractions, infinite fractions, and rational approximations -->
<p>The irrationals, in this way, are integral to the real numbers. Not just in the sense that we have to include them, but in that they <strong>complete</strong> the real numbers. That least upper bound property we discussed above is what is referred to as the <strong>completeness of the real numbers</strong> (which can be an axiom or property derivative of other axioms, but either way is what characterizes the reals). </p>
<p>And yet, despite their utility, irrational numbers are still pretty mysterious. We know all rational numbers take on a certain form of $\frac{p}{q}$. Even complex numbers all reduce to some $a + bi$. But irrational numbers can take on any number of forms. </p>
<ul>
<li><a href="https://xperimex.com/blog/real-induction/#proof-by-infinite-descent">Taking the square root of any non-square number is irrational</a></li>
<li>The golden ratio $\varphi$ is irrational</li>
<li>$e = \lim\limits_{n\to\infty} \left(1+\frac{1}{n} \right)^n = \sum_{n = 0}^{\infty} \frac{1}{n!} \approx 2.71828\cdots \ $ is irrational</li>
<li>$\pi$ as the ratio of a circle&#39;s circumference to its diameter is irrational</li>
</ul>
<p>Irrational numbers can pop up almost anywhere. Though, we might be getting a bit ahead of ourselves. We have a sort of &quot;standard form&quot; of irrational numbers given by our decimal expansions and our above claim: a number is irrational if and only if it has a non-repeating decimal part. But it&#39;s not like we can <em>a priori</em> check a decimal expansion is infinite to prove a number is irrational; it&#39;s usually shown that infinite decimal expansions are a consequence of irrationality.</p>
<h2 id="continued-infinite-and-reasonable-fractions">Continued, Infinite, and Reasonable Fractions</h2>
<p>So, while we showed that we <em>in theory</em> need irrational numbers, <em>in practice</em> representing them and using them seem far more tedious and annoying to work with.</p>
<p>And further, if you&#39;re just an engineer, astronomer, or even a mathematician that needs <em>some concrete number</em> to work with, rational numbers get us most of the way there for what we need. Why not just take some arbitrary decimal cut off? Most people only <em>know</em> $\pi$ up to $3.14$ anyway. </p>
<p>$3.14$ is pretty good, but an arguably better approximation is the famous $\frac{22}{7} \approx 3.14286$. Sure, it might be further off from $\pi$ than $3.14$, but it is a rather simple fraction that can make calculations easier and more convenient. You could go even further and get $\frac{355}{113} \approx 3.1415929$ which is good up to 6 decimals. Can we get any better?</p>
<p>So before we get any further in directly discussing irrationals, let&#39;s take a minute to talk more about rational numbers and their relationship with irrationals. From this, we&#39;ll see another nice property of irrational numbers that will help us along our way in a similar, but stronger way compared to decimal expansions.</p>
<h3 id="repeating-decimals-leftrightarrow-rationals">Repeating Decimals $\Leftrightarrow$ Rationals</h3>
<p>We alread proved that repeating and terminating decimals correspond to some rational number. So as a first step, it might be worth thinking about how we might go to and from fractions and these nice decimals before considering how we might do something with the weird and infinite decimals of irrationals. </p>
<p>Finite decimals are easy: just take the least power of 10 in it&#39;s decimal expansion and put it in the denominator of the digits. $.5 = \frac{5}{10^1} = \frac{1}{2}$, and $1.562782 = \frac{1562782}{10^6}$. Not particularly helpful. </p>
<p>If we have a repeating decimal, it&#39;s slightly trickier, but our proof above showing they are rational essentially tells us how to do the conversion. </p>
<ul>
<li>Consider the number $x = 2.642857 \overline{142857}$ </li>
<li>Using the above notation, $a=2$, $n=6$, $m=6$</li>
<li>So $N = 10^{6+6}\cdot 2 + 642857142857 - (10^6\cdot 2 + 642857)$</li>
<li>All together, we get that $x = \frac{N}{(10^6 - 1)10^6} = \frac{37}{14}$</li>
</ul>
<p>You can also use geometric series to get the same answer, using the fact that the repetitions in the decimal are all separated by a ratio of $10^{-m}$ (for example, $0.\overline{142857} = 10^{-6} \cdot \sum_{n=0}^{\infty}142857\cdot 10^{-6n}$, and since $10^{-6}&lt;1$, we get that it&#39;s equal to $10^{-6} \cdot 142857\cdot \frac{1}{1 - 10^{-6n}} = \frac{142857}{999999} = \frac{1}{7}$).</p>
<p>Though, we should expect that we can get these exact rationals since we already proved that finite and repeating decimals all are rational.</p>
<h3 id="rational-approximations">Rational Approximations</h3>
<p>Now irrational numbers, on the other hand, by definition, will not have a rational form. So now we will actually need rational approximations. But finding those approximations, is not particularly easily. In particular, for irrational $x$, we want to find a rational $\frac{p}{q}$ such that $\left| x - \frac{p}{q} \right| &lt; \epsilon$. At the very least, we know such rationals exist for any $\epsilon &gt; 0$, since the rationals are dense in $\mathbb{R}$; there is always a(n infinite amount of) rational(s) in the interval $\left( x - \epsilon, x + \epsilon \right)$.</p>
<!-- But, again, this is not particularly helpful for our task. We were hoping to _find_ something along the lines of $\frac{22}{7}$ for $\pi$, and figure out the level of precision our approximations give us. What determines our precision? Well, obviously, it should be the denominator $q$; as we let $p$ vary, the numbers we get increment by $\frac{1}{q}$. So we know for a fact that we can get rational at least within $\frac{1}{2q}$ of an irrational number for a given denominator $q$. That is because $x$ must be in some interval $\left( \frac{p+1}{q}, \frac{p+1}{q} \right)$. -->
<p>But we don&#39;t want to waste our time with &quot;bad&quot; approximations. Notice that for any denominator $q$, we can find a $p$ such that $\left| x - \frac{p}{q} \right| \leq \frac{1}{2q}$. This is just a result that if we divide the real numbers into intervals of size $\frac{1}{q}$, our number $x$ will fall in one of them and be closer to one side of the interval than the other.</p>
<p>It turns out though, we can find approximations that are far more &quot;efficient&quot; and get us much closer to our irrational number than just $\frac{1}{2q}$ for their denominator $q$.</p>
<p><strong>Dirichlet&#39;s Approximation Theorem:</strong> $\forall x \in \mathbb{R}$ and $\forall N \in \mathbb{N}$, there are integers $p$ and $q$ such that $0 &lt; q \leq N$ and $\left|qx - p \right| &lt; \frac{1}{N}$.</p>
<p>As a consequence, we then have rational approximations $\frac{p}{q}$ that get us within $\frac{1}{q^2}$ of our irrational $x$ since $q\leq N$ implies</p>
<center>

$$\left|qx - p \right| &lt; \frac{1}{N} \Rightarrow \left|x - \frac{p}{q} \right| &lt; \frac{1}{qN} \leq \frac{1}{q^2}$$

</center>

<p><strong>Proof:</strong> Pick $x\in \mathbb{R}$ and $N \in \mathbb{N}$. We will prove this using the Pigeonhole Principle. Note that any integer $n$ can be written as a fraction with any denominator $k$ as $\frac{nk}{k}$. So all we care about is approximating the fractional part of $x$, call it $\{x\} \in [0,1)$. Now divide the interval $[0,1)$ into $N$ equal subintervals of length $\frac{1}{N}$ i.e.</p>
<center>

$[0,1) = \left[0, \frac{1}{N} \right) \cup \left[\frac{1}{N}, \frac{2}{N} \right) \cup \cdots \cup \left[\frac{N-1}{N}, 1 \right)$

</center>

<p>Now consider the set of $N+1$ numbers $kx$ for $0\leq k \leq N$, and in particular their fractional parts $\{kx\}$. By the Pigeonhole Principle, at least two of these fractional parts $\{k_1 x\}, \{k_2 x\}$ lie in the same $\frac{1}{N}$-subinterval of $[0,1)$ (without loss of generality, we can pick $k_1 &gt; k_2$). </p>
<p>Note, we can write $\{kx\} = kx - \lfloor kx \rfloor = kx - j$ for some interger $j$. So if two fractional parts lie in the same subinterval, then what we have is </p>
<center>

$$\left|\{k_1 x\} - \{k_2 x\}\right| = \left|(k_1 x - j_1) - (k_2 x - j_2)\right| = \left|(k_1 - k_2)x - (j_1 - j_2)\right| &lt; \frac{1}{N}$$

</center>

<p>So if we let $q = k_1 - k_2$, and $p = j_1 - j_2$, then we have $0 &lt; q \leq N$ and</p>
<center>

$$\left|\{k_1 x\} - \{k_2 x\}\right| = \left|qx - p \right| &lt; \frac{1}{N}$$

</center>

<p>which is exactly what we wanted to show.</p>
<center>
$\blacksquare$
</center>

<p>Also, it&#39;s worth noting that there are infinitely many of these approximations, despite this just being an existence proof of <em>at least</em> one such pair $p,q$ that bound $\left|x - \frac{p}{q} \right| &lt; \frac{1}{q^2}$. This can be quickly noticed since for a given $N_0$, Dirichlet&#39;s theorem says that there is at least one pair of $p_0,q_0$ such that $\left| q_0x - p_0 \right| &lt; \frac{1}{N_0}$. But then, if we increase $N_0$ to $N_1$ large enough such that $\left| q_0x - p_0 \right| \geq \frac{1}{N_1}$, then Dirichlet&#39;s theorem ensures that there is some new pair of numbers such that $\left| q_1x - p_1 \right| &lt; \frac{1}{N_1}$. And we can continue this forever.</p>
<hr>
<p>As an interesting aside, this can also be used to show that rationals are in some ways worse than irrationals at being approximated by <em>other</em> rationals. Of course, if we &quot;approximate&quot; a rational with itself, it trivially holds that it is the &quot;best&quot; approximation. But concretely, if we have a rational $x = \frac{a}{b}$ and another rational $\frac{p}{q} \neq x$, then we get that </p>
<center>

$\frac{p}{q} \neq x = \frac{a}{b} \Rightarrow pb - qa \neq 0$

</center>

<p>In particular, since $p,q,a,b$ are all integers, so would that difference above be, and so we can conclude that $|pb - qa| \geq 1$. So all together,</p>
<center>

$\left|qx - p \right|$ $ = \left| \large{\frac{qa - pb}{b}} \right|$ $\geq \large{\frac{1}{b}}$

</center>

<p>which is bounded away from 0, regardless of $q$. Which shouldn&#39;t be that surprising thinking through that $p,q$ are integers so that difference in distance should only have a non-integer part that is exactly proportional to the denominator $\frac{1}{b}$.</p>
<h3 id="best-rational-approximations">Best Rational Approximations</h3>
<p>Dirichlet&#39;s Approximation Theorem tells us that we have stronger candidates than others for rationally approximating irrationals. Which is great and all, but can we give a more specific criterion to single out these &quot;better&quot; approximations? Or at the very least, approximations that we would prefer using?</p>
<p>We won&#39;t use the approximation that Dirichlet&#39;s Theorem would suggest above, as in using something &quot;efficient&quot; that gets us closer to the number we are approximating more than we&#39;d expect it to. And besides, our proof above doesn&#39;t actually tell us how to find these good approximations <strong>since we have no control for our denominator $q$, but rather only an upper bound for $q$ with our choice of $N$</strong>. In particular, it also doesn&#39;t tell us how good our approximations are to <em>other</em> Dirichlet approximations; it could be the case that one approximation from Dirichlet&#39;s theorem is better than another despite having a smaller denominator (and so is in some way more preferable).</p>
<p>Probably the easiest metric of a <strong>best rational approximation</strong> of a number in this case would be that it is the best approximation for the smallest denominator found yet. Ideally, we want to work with &quot;simple&quot; fractions (i.e. with small denominators). So we say a rational approximation $\frac{n}{d}$ for a real number $x$ is best if $\frac{n}{d}$ is closer to $x$ than any other fraction with denominator less than $d$. If you want something more concrete, $\frac{n}{d}$ is a best approximation for $x$ if </p>
<center>

<!-- $\left\\{ \frac{p}{q} \in \mathbb{Q} \ | \ \left| \frac{p}{q} - x \right| < \left| \frac{n}{d} - x \right| \ , \ 0 \neq q < d \right\\} = \emptyset$ -->

$\large{\frac{n}{d}}$ $= \min\left\{ \left| x - \frac{p}{q} \right| \ : \ q \leq d  \right\}$

</center>

<p>To really get the point across, $\frac{p}{q}$ is a best rational approximation if it is not possible to get a better approximation using a smaller denominator. This is part of the reason why $\frac{22}{7}$ is so convenient to approximate $\pi$ as it is still a rather simple and easy-to-work with fraction, but is in a sense better than any possibly simpler fraction. Again, this is great to have, but we still don&#39;t have a way of finding these approximations any better than just brute force checking every other simpler fraction.</p>
<p>To find these approximations, we&#39;ll have to take a slight detour that perhaps is the closest link between representing any real number with rationals that you might have seen before.</p>
<h2 id="continued-fractions">Continued Fractions</h2>
<p>Consider one of our favorite irrational numbers that we might want to approximate: $\sqrt{2}$. Before trying to find approximations or anything, notice that $\sqrt{2} - 1 = \frac{1}{1 + \sqrt{2}}$. </p>
<p>Now hold on. We just found that $\sqrt{2} = 1 + \frac{1}{1 + \sqrt{2}}$. If $\sqrt{2}$ equals that fraction on the righthand side, then we can just replace an instance of $\sqrt{2}$ with that same fraction:</p>
<center>

$$
\sqrt{2} = 1 + \large{\frac{1}{1 + (1 + \frac{1}{1 + \sqrt{2}})}}
$$

</center>

<p>And again:</p>
<center>

$$
\sqrt{2} = 1 + \large{\frac{1}{2 + \frac{1}{1 + (1 + \frac{1}{1 + \sqrt{2}})}}}
$$

</center>

<p>And can keep doing this forever:</p>
<center>

$$
\sqrt{2} = 1 + \large{\frac{1}{2 + \frac{1}{2 + \frac{1}{2 + \frac{1}{\ddots}}}}}
$$

</center>

<p>This is a <strong>continued fraction</strong> for $\sqrt{2}$. This particular one is the <strong>canonical</strong> or <strong>simple</strong> continued fraction for $\sqrt{2}$ since all the numerators are 1. The <strong>generalized continued fraction</strong> allows for any numerator. Perhaps an even more famous continued fraction is that for the golden ratio $\varphi$: </p>
<center>

$$
\varphi = \frac{1 + \sqrt{5}}{2} = 1 + \large{\frac{1}{1 + \frac{1}{1 + \frac{1}{1 + \frac{1}{\ddots}}}}}
$$

</center>

<p>As shorthand, simple continued fractions are sometimes written as $\sqrt{2} = [1;2,2,2,2,\ldots]$ to indicate the coefficients. So likewise, $\varphi = [1;1,1,1,1,\ldots]$.</p>
<h3 id="properties-of-continued-fractions">Properties of Continued Fractions</h3>
<p>Working with things that <em>look</em> like rational numbers should key us into that this is closer to where we want to be looking. And like decimals, continued fractions gives us a nice dichotomy between the rational and irrational.</p>
<!-- prove fintie iff rational -->
<p><strong>Claim:</strong> A number is rational if and only if its simple continued fraction representation is finite.</p>
<p><strong>Proof:</strong> $(\Leftarrow)$ If the continued fraction is finite i.e.</p>
<center>

$x = a_1 + $ $\large{ \frac{1}{a_2 + \frac{1}{a_3 + \frac{1}{\frac{\ddots}{a_{n-1}+\frac{1}{a_n}}}}}}$

</center>

<p>Then we can just collapse the continued fraction by creating common denominators and simplifying with normal fraction rules, showing $x$ is rational.</p>
<p>$(\Rightarrow)$ The idea is we&#39;ll continuously separate our fraction into its integer and fractional parts, and continue to reduce the fractional part. As an example,</p>
<center>

$\frac{19}{7} = 2 + \frac{5}{7} = 2 + \frac{1}{\frac{7}{5}} = 2 + \frac{1}{1 + \frac{2}{5}} = 2 + \frac{1}{1 + \frac{1}{\frac{5}{2}}} = 2 + \frac{1}{1 + \frac{1}{2 + \frac{1}{2}}}$

</center>

<p>If $x = \frac{p}{q}$ is rational, then we can repeatedly apply the division algorithm to create our continued fraction. So write $p = a_1 q + r_1$ for $0\leq r_1 &lt; q$. Hence, we can write $\frac{p}{q} = a_1 + \frac{r_1}{q} = a_1 + \frac{1}{\frac{q}{r_1}}$. Again, we can repeat the division algorithm and write $q = a_2 r_1 + r_2$ for $0 \leq r_2 &lt; r_1$. </p>
<p>To put it more neatly, write the following division algorithm steps:</p>
<center>
$
\begin{array}{cc}
p = a_1 q + r_1 &amp; 0 \leq r_1 &lt; q \\
q = a_2 r_1 + r_2 &amp; 0 \leq r_2 &lt; r_1 \\
r_1 = a_3 r_2 + r_3 &amp; 0 \leq r_3 &lt; r_2 \\
\vdots &amp; \vdots  \\
r_{n-3} = a_{n-1} r_{n-2} + r_{n-1} &amp; 0 \leq r_{n-1} &lt; r_{n-2}  \\
r_{n-2} = a_n r_{n-1}
\end{array}
$
</center>

<p>Note since $r_1 &gt; r_2 &gt; \cdots &gt; r_{n-1}$ form a sequence strictly decreasing and non-negative integers, this process must eventually terminate with all $r_m = 0$ after a certain point <strong>in a finite number of steps</strong> (this is what justifies using the division algorithm to find the GCD of two numbers). Once our algorithm terminates in a finite number of steps (this is what keeps our continued fraction finite), it&#39;s just a matter of writing out the continued fraction:</p>
<center>

$x = \frac{p}{q} = a_1 + \frac{r_1}{q} = a_1 + $ $\large{ \frac{1}{a_2 + \frac{1}{a_3 + \frac{1}{\frac{\ddots}{a_{n-1}+\frac{1}{a_n}}}}}}$

</center>

<p>and we&#39;re done.</p>
<center>
$\blacksquare$
</center>

<p>So this actually gives us a direct proof that $\sqrt{2}$ is irrational with its continued fraction: its simple continued fraction is infinite, and so it must be irrational.</p>
<h2 id="more-on-irrational-continued-fractions">More on Irrational Continued Fractions</h2>
<!-- This is great, but we never actually talked about not only finding these infinite continued fractions (which always is a challenge when infinity is involved), but actually showing that their convergence to a number is genuine. -->
<p>Let&#39;s go back to our proof that all rational numbers have finite continued fraction expansions. Another way we can see this fact is by constructing continued fractinos for irrational numbers, and we do so in almost the exact same way we did for rationals. The idea in using the division algorithm is that we separate our number $x$ into its integer and fractional component, and then invert the fractional component (which is less than 1, so inverting it gives us a number greater than one to keep separating into integer and fractional parts). I.e. first write</p>
<center>

$x = \lfloor x \rfloor + x - \lfloor x \rfloor = \lfloor x \rfloor +$ $\large{\frac{1}{\frac{1}{x - \lfloor x \rfloor}}}$

</center>

<p>and then repeat this exact writing process on $x - \lfloor x \rfloor$. But since $x - \lfloor x \rfloor$ is also irrational, and so will all future denominators at each step. The only way this process terminates is if our step $x - \lfloor x \rfloor = 0$ which is rational, and hence can&#39;t happen.</p>
<p><strong>Claim:</strong> Let $x$ be irrational. Let $x_0 = x, \  a_k = \lfloor x_k \rfloor, \ x_{k+1} = \frac{1}{x_k - a_k}$. Then for all $k$</p>
<center>

$x = [a_0; a_1, a_2, \ldots, a_{k-1}, x_k] = a_0 + $ $\large{ \frac{1}{a_1 + \frac{1}{a_2 + \frac{1}{\frac{\ddots}{a_{k-1}+\frac{1}{x_k}}}}}}$

</center>

<p><strong>Proof:</strong> This follows immediately from our construction above: separate the integer part and invert the fractional. It clearly holds for $k=0$, since $x = x_0$. Say this holds for $k$. Then $x_{k+1} = \frac{1}{x_k - a_k} \Rightarrow x_k = a_k + \frac{1}{x_{k+1}}$ and so</p>
<center>

$x = [a_0; a_1, a_2, \ldots, x_k] = [a_0; a_1, a_2, \ldots, a_k + \frac{1}{x_{k+1}}] = [a_0; a_1, a_2, \ldots, a_k, x_{k+1}]$.

</center>

<center>
$\blacksquare$
</center>

<p></br></p>
<p>Then it is not too hard to show that we can extend this to the infinite continued fraction in the way we&#39;d want to.</p>
<p><strong>Claim:</strong> $[a_0; a_1, a_2, \ldots] = \lim\limits_{n\to\infty} [a_0; a_1, a_2, \ldots, a_n] = x$</p>
<hr>
<p>Before we continue into the infinite, we&#39;ll need some tools about the finite first that we will extend with limits. The truncated continued fractions of $x$ called the <strong>convergents</strong> of the continued fraction. The nth convergent of a continued fraction is </p>
<center>

$c_n = \frac{p_n}{q_n} = [a_0; a_1, a_2, \ldots, a_n] = a_0 + $ $\large{ \frac{1}{a_1 + \frac{1}{a_2 + \frac{1}{\frac{\ddots}{a_{n-1}+\frac{1}{a_n}}}}}}$

</center>

<p>A convergent is just the initial segment of the continued fraction up to the $nth$ denominator. One useful fact we will need is the recursive formula for the numerator $p_n$ and denominator $q_n$ of these convergents (since the direct formula can get very complicated in simplifying it).</p>
<p><strong>Lemma:</strong> For an infinite continued fraction $[a_0; a_1, a_2, \ldots]$ with $a_i &gt; 0 \  \forall i &gt; 1$, let $c_n = \frac{p_n}{q_n}$ be the nth convergent. We then have the following recurrence:</p>
<center>
$
\begin{array}{c|c}
p_0 = a_0 &amp; q_0 = 1 \\
p_1 = a_1 a_0 + 1 &amp; q_1 = a_1 \\
p_n = a_n p_{n-1} + p_{n-2} &amp; q_n = a_n q_{n-1} + q_{n-2} \\
\end{array}
$
</center>

<p><strong>Proof:</strong> We&#39;ll prove this inductively. Note when I equate two fractions here, I mean to literally equate the numerators and denominators just as shorthand to show the two recursions at once (and simultaneously link it back to the convergent directly).</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <strong>Base Case:</strong> We just quickly check this $c_0 = \frac{a_0}{1} = \frac{p_0}{q_0}$. $c_1 = a_0 + \frac{1}{a_1} = \frac{a_1 a_0 + 1}{a_1} = \frac{p_1}{q_1}$.</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <strong>Inductive Step:</strong> Say this is true for $c_n = \frac{p_n}{q_n} = \frac{a_n p_{n-1} + p_{n-2}}{a_n q_{n-1} + q_{n-2}}$. Now consider $c_{n+1} = [a_0, a_1, \ldots, a_n, a_{n+1}]$. Note we can obtain $c_{n+1}$ from $c_n$ by replacing $a_n$ with $a_n + \frac{1}{a_{n+1}}$. That is, we can do a substitution trick like we did before, and write $c_{n+1} = [a_0, a_1, \ldots, a_n + \frac{1}{a_{n+1}}]$. Fortunately, by the inductive hypothesis, we have our numerator and denominator of $c_n$ in a form that is dependent on $a_n$ and makes this substitution possible (note that $p_{n-1}$, $p_{n-2}$, $q_{n-1}$, $q_{n-2}$ don&#39;t depend on $a_n$, so they remain unaffected by this substitution).</p>
<center>

<!-- $c_{n+1} = $ $\large{\frac{\left(a_n + \frac{1}{a_{n+1}}\right) p_{n-1} + p_{n-2}}{\left(a_n + \frac{1}{a_{n+1}}\right) q_{n-1} + q_{n-2}}}$ $ = $ $\large{\frac{\left(a_n p_{n-1} + p_{n-2} \right) + \frac{1}{a_{n+1}} p_{n-1}}{\left(a_n q_{n-1} + q_{n-2} \right) + \frac{1}{a_{n+1}} q_{n-1}}}$ $ = $ $\large{\frac{p_n + \frac{1}{a_{n+1}} p_{n-1}}{q_n + \frac{1}{a_{n+1}} q_{n-1}}}$ $ = $ $\large{\frac{a_{n+1} p_n + p_{n-1}}{a_{n+1} q_n + q_{n-1}}}$  -->

$\begin{align}
c_{n+1} &amp;  = \frac{\left(a_n + \frac{1}{a_{n+1}}\right) p_{n-1} + p_{n-2}}{\left(a_n + \frac{1}{a_{n+1}}\right) q_{n-1} + q_{n-2}} \\
&amp; = \frac{\left(a_n p_{n-1} + p_{n-2} \right) + \frac{1}{a_{n+1}} p_{n-1}}{\left(a_n q_{n-1} + q_{n-2} \right) + \frac{1}{a_{n+1}} q_{n-1}} \\
&amp; = \frac{p_n + \frac{1}{a_{n+1}} p_{n-1}}{q_n + \frac{1}{a_{n+1}} q_{n-1}} \\
\frac{p_n}{q_n} &amp; = \frac{a_{n+1} p_n + p_{n-1}}{a_{n+1} q_n + q_{n-1}}

\end{align}$


</center>

<p>Giving us exactly what we wanted. </p>
<center>
$\blacksquare$
</center>

<p>These recursions give us some very useful ways of characterizing convergents, since without them, it isn&#39;t hard to imagine how complicated the numerators and denominators might become when trying to collapse the continued fraction.</p>
<p><strong>Claim:</strong> $p_{n-1} q_n - q_{n-1} p_n = (-1)^n$</p>
<p><strong>Proof:</strong> As expected, we&#39;ll use induction:</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <strong>Base Case:</strong> For $n=1$, we get $p_0 q_1 - q_0 p_1 = a_0 a_1 - 1 \cdot (a_1 a_0 + 1) = -1$.
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <strong>Inductive Step:</strong> Suppose this is true for $n$. Then using our recursions, we can show this holds for $n+1$:</p>
<center>

$\begin{align}

p_{n} q_{n+1} - q_{n} p_{n+1} &amp; = p_n (a_{n+1} q_{n} + q_{n-1}) - q_n (a_{n+1} p_{n} + p_{n-1}) \\
&amp; = p_n q_{n-1} - q_n p_{n-1} \\
&amp; = (-1) \cdot (p_{n-1} q_n - q_{n-1} p_n) \\
&amp; = (-1) \cdot (-1)^n \\
&amp; = (-1)^{n+1}

\end{align}$

</br>

$\blacksquare$

</center>

<p>This fact also then immediately tells us that $\gcd (p_n, q_n) = 1 $ and that they are coprime, so $c_n = \frac{p_n}{q_n}$ is always in lowest terms. It also gives us a nice relation between adjacent convergents:</p>
<center>

$\begin{align}
c_n - c_{n-1} = \frac{p_n}{q_n} - \frac{p_{n-1}}{q_{n-1}} = \frac{p_n q_{n-1} - q_n p_{n-1}}{q_n q_{n-1}} = \frac{(-1)^{n+1}}{q_n q_{n-1}}
\end{align}$

</center>

<p></br></p>
<p>This fact that $c_n - c_{n-1} = \frac{(-1)^{n+1}}{q_n q_{n-1}}$ will get arbitrarily small also shows they form a Cauchy sequence (the formal proof is just using this bound with the triangle inequality) and hence converge $\lim\limits_{n\to\infty} c_n$ exists. Below we&#39;ll show that they converge to the limit we expect.</p>
<p>Taking a minute to give some terminology and the above recurrence will help us in the future.</p>
<hr>
<p><strong>Claim:</strong> Using the $a_i$, $x_i$ defined above, $[a_0; a_1, a_2, \ldots] = \lim\limits_{n\to\infty} [a_0; a_1, a_2, \ldots, a_n] = x$</p>
<p><strong>Proof:</strong> As with any question about infinity, we look at the partial, in-between steps and consider the formal limit. That means our convergents $c_n$ i.e. we want to show $\left| x - c_n \right| = \left| x - \frac{p_n}{q_n} \right| \rightarrow 0$. </p>
<p>First, note clearly the $x_n$ is irrational for all $n$. Second, we&#39;ll show $a_n &gt; 0$ for all $n$ so we can use our recursive formula of convergents above. This follows because our algorithm essentially takes the fractional part of our number (which is less than 1), and inverts it (making it greater than 1) at the next step: since $a_k = \lfloor x_k \rfloor$, we have $a_k &lt; x_k &lt; a_k + 1$ (we get a strict lower inequality by the irrationality of $x_k$). So $0 &lt; x_k - a_k &lt; 1$. Hence, $x_{k+1} = \frac{1}{x_k - a_k} &gt; 1$, and therefore $a_{k + 1} = \lfloor x_{k+1} \rfloor \geq 1$.</p>
<p>So we can use our recursive formulas for convergents we proved above. Also using our &quot;finite&quot; continued fraction from before, we can write</p>
<center>

$x = [a_0; a_1, a_2, \ldots, a_n, x_{n+1}] =$ $\large{\frac{x_{n+1} p_n + p_{n-1}}{x_{n+1} q_n + q_{n-1}}}$

</center>

<p>Therefore,</p>
<center>

$\begin{align}

x - \frac{p_n}{q_n} &amp; = \frac{x_{n+1} p_n + p_{n-1}}{x_{n+1} q_n + q_{n-1}} - \frac{p_n}{q_n} \\
&amp; = \frac{x_{n+1} p_n q_n + p_{n-1} q_n -  x_{n+1} q_n p_n - q_{n-1} p_n}{(x_{n+1} q_n + q_{n-1})q_n} \\
&amp; = \frac{p_{n-1} q_n - q_{n-1} p_n}{(x_{n+1} q_n + q_{n-1})q_n} \\
&amp; = \frac{(-1)^n}{(x_{n+1} q_n + q_{n-1})q_n} \\
\end{align}$

</center>

<p>The last equality we showed above with our recursions. Taking absolute values,</p>
<center>

$\left| x - \frac{p_n}{q_n} \right| =$ $\left| \large{\frac{1}{(x_{n+1} q_n + q_{n-1}) q_n}} \right|$

</center>

<p>Also, $x_{n+1} &gt; \lfloor x_{n+1} \rfloor = a_{n+1}$, so $x_{n+1} q_n + q_{n-1} &gt; a_{n+1} q_n + q_{n-1} = q_{n+1}$:</p>
<center>

$\left| x - \frac{p_n}{q_n} \right| =$ $\left| \large{\frac{1}{(x_{n+1} q_n + q_{n-1}) q_n}} \right|$ $ &lt; $  $\large{\frac{1}{q_{n+1} q_n}}$

</center>

<p>Next, note that $q_n \geq n$ for $n \geq 1$:</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>Lemma:</strong> $q_n \geq n$ for $n \geq 1$.</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>Proof:</strong> $q_1 = a_1 \geq 1$ as shown earlier, so we have a base case established. Say $q_k \geq k$ for $k\leq n$. Then $q_{n+1} = a_{n+1}q_n + q_{n-1} \geq 1 \cdot n + n-1 \geq n+1$. $\blacksquare$</p>
<p>Finally, </p>
<center>

$\left| x - \frac{p_n}{q_n} \right| &lt; $  $\large{\frac{1}{q_{n+1} q_n}}$ $\leq$ $\large{\frac{1}{(n+1)n}}$

</center>

<p>Giving the limit</p>
<center>

$\lim\limits_{n\to\infty} \left| x - \frac{p_n}{q_n} \right| = 0$

</br>
</br>

$\blacksquare$
</center>

<p>So we&#39;re actually justified in using these infinite continued fractions in the way we want to, and generate them in a semi-algorithmic way:</p>
<center>

$\begin{align}

\pi &amp; = 3 + .141592 \ldots \\
&amp; = 3 + \frac{1}{\frac{1}{.141592\ldots}} = 3 + \frac{1}{7 + .062513\ldots} \\
&amp; = 3 + \frac{1}{7 + \frac{1}{\frac{1}{.062513\ldots}}} = 3 + \frac{1}{7 + \frac{1}{15 + .996594\ldots}} \\
&amp; = 3 + \frac{1}{7 + \frac{1}{15 + \frac{1}{1 + \frac{1}{\ddots}}}}

\end{align}$

<!-- this is currently relies on knowing decimal expansion for π, which can be arguably harder to find as well so will explain how to find them -->

</center>

<p>I say semi-algorithmic since the way I presented above already relies on having the exact value of $\pi$ in decimal, which can be arguably harder to find. It&#39;s good enough to get us as many coefficients as we&#39;ll practically need, but we&#39;ll address this problem later.</p>
<!-- maybe prove all canonical ones converge -->
<!-- all real numbers have continued fraction represntaiton -->
<!-- show quadratic ones are periodic -->
<!-- talk about best rational approximations -->
<!-- below are most important! -->
<!-- talk about generating infinite fractions -->
<!-- might be worth mentioning how golden ratio is most irrational number -->
<h2 id="best-rational-approximations">Best Rational Approximations</h2>
<p>Now the reason we went through all this trouble is because <strong>continued fractions have the surprising ability to generate best rational approximations systematically</strong>. Remember, we say a rational approximation $\frac{n}{d}$ for a real number $x$ is best if $\frac{n}{d}$ is closer to $x$ than any other fraction with denominator less than $d$. </p>
<p><strong>Definition:</strong> We say $\frac{p}{q}$ is a <strong>best rational approximation</strong> for $x$ if </p>
<center>

$\large{\frac{n}{d}}$ $= \min\left\{ \left| x - \frac{p}{q} \right| \ : \ q \leq d  \right\}$

</center>


<!-- In a way that will be more helpful and familiar to our work with Dirichlet approximations, we say $\frac{p}{q}$ is a best rational approximation for $x$ if $\left|qx - p \right| \leq \left|q'x - p' \right|$ for all $q' \leq q$. -->
<p>Now here&#39;s the remarkable fact:</p>
<p><strong>Theorem:</strong> Write an irrational number $x = [a_0; a_1, a_2, \ldots]$ as its continued fraction expansion. Then for any convergent $c_n = \frac{p_n}{q_n}$ and any rational $\frac{a}{b}$ with $b &lt; q_{n+1}$, then $\left| q_n x - p_n \right| \leq \left| bx - a \right|$.</p>
<p>This is actually a stronger statement, since it&#39;s not only a best rational approximation, but it is also a better rational approximation than some denominators <em>greater</em> than $q_n$. It should not be surprising that $q_{n+1} &gt; q_n$ for all $n$ (just think about the process involved in collapsing a continued fraction; or show by induction with the recursion formulas). But what our claim says is that for not only rational approximations of denominator less than $q_n$, but <em>also</em> for some denominators <em>greater</em> than $q_n$, $\frac{p_n}{q_n}$ is still a better approximation for $x$. Which is surprising, since that would mean even if we divide the real numbers into smaller boxes, sometimes our numbers will be closer to the edges of the bigger box. It&#39;s like saying that a steak knife can get you a more precise cut than some X-Acto knives.</p>
<!-- https://proofwiki.org/wiki/Denominators_of_Simple_Continued_Fraction_are_Strictly_Increasing -->
<!-- This actually is a stronger statement than $\frac{p_n}{q_n}$ being a best rational approximation for $x$. If we only consider $b \leq q_n$ and let $\left| q_n x - p_n \right| = \alpha$, and  $\left| bx - a \right| = \beta$, then we get 

<center>

$\begin{align}

\left| x - \frac{p_n}{q_n} \right| = \frac{\alpha}{q_n} \leq \frac{\beta}{b} = \left|x - \frac{a}{b} \right|

\end{align}$

</center>

$\frac{\alpha}{q_n} \leq \frac{\beta}{b}$ follows since $\alpha \leq \beta$ and $b \leq q_n$, giving us our best rational approximation property. But note by the magnitude:  -->
<p><strong>Proof:</strong> Let $\frac{a}{b}$ be a rational number in lowest terms such that $b &lt; q_{n+1}$. We&#39;ll also assume $a \neq p_n$ and $b \neq q_n$ (since then we clearly have equality). We&#39;ll rewrite $a,b$ in terms of new numbers $r,s \in \mathbb{R}$ that we define by the following system of equations:</p>
<center>

$\begin{align}

a &amp; = r p_n + s p_{n+1} \\
b &amp; = r q_n + s q_{n+1} \\

\end{align}$

</center>

<p>$r,s$ exist since that system of equations is equivalent to the matrix system</p>
<center>

$
\begin{bmatrix}
p_n &amp; p_{n+1} \\
q_n &amp; q_{n+1}
\end{bmatrix}
\begin{bmatrix}
r \\
s
\end{bmatrix}
=
\begin{bmatrix}
a \\
b
\end{bmatrix}
$

</center>

<p>and we showed that the determinant $p_n q_{n+1} - q_n p_{n+1} = (-1)^{n+1} \neq 0$ and so is invertible. Now if we solve for $r,s$ (either with matrices or directly), we see that</p>
<center>

<!-- $a q_n - b p_n = s(p_{n+1} q_n - q_{n+1} p_n) = s(-1)^{n+2}$ -->

$
\begin{bmatrix}
r \\
s
\end{bmatrix}
=
\begin{bmatrix}
p_n &amp; p_{n+1} \\
q_n &amp; q_{n+1}
\end{bmatrix}^{-1}
\begin{bmatrix}
a \\
b
\end{bmatrix}
= \pm
\begin{bmatrix}
q_{n+1} &amp; -p_{n+1} \\
-q_n &amp; p_n
\end{bmatrix}
\begin{bmatrix}
a \\
b
\end{bmatrix}
= \pm
\begin{bmatrix}
q_{n+1}a - p_{n+1}b \\
-q_n a + p_n b
\end{bmatrix}
$

</center>

<p>So $r,s$ are integers.</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>Claim:</strong> $r,s \neq 0$.</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>Proof:</strong> If $r = 0$, then $q_{n+1}a = p_{n+1}b$. But since $p_{n+1}$ and $q_{n+1}$ don&#39;t divide each other (we proved earlier they were coprime), we have $q_{n+1}$ divides $b$, contradicting the assumption that $b &lt; q_{n+1}$. If $s=0$, then we have $\frac{a}{b} = \frac{p_n}{q_n}$ which we already excluded in our assumptions. $\blacksquare$</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>Claim:</strong> $r$ and $s$ have opposite signs.</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>Proof:</strong> We&#39;ll just check the two cases.</p>
<ul>
<li>If $s &gt; 0$, then $s \geq 1$. Therefore $sq_{n+1} \geq q_{n+1} &gt; b$, and thus $b = rq_n + sq_{n+1}$ implies that $rq_n = b - sq_{n+1} &lt; 0$. Since $q_n &gt; 0$, we must have $r&lt;0$. </li>
<li>If $s &lt; 0$, then $-sq_{n+1} &gt; 0$. Hence we have $rq_n = b - sq_{n+1} &gt; 0$. Thus $r &gt; 0$. $\blacksquare$</li>
</ul>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>Claim:</strong> $q_n x - p_n$ and $q_{n+1} x - p_{n+1}$ have opposite signs.</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>Proof:</strong> Note we saw earlier that the difference between consecutive convergents alternate in sign: </p>
<center>
$\begin{align}
c_n - c_{n-1} = \frac{(-1)^{n+1}}{q_n q_{n-1}}
\end{align}$
</center>

<p>That is, the convergents take turns being greater or lesser than the previous convergent. What this means is that our convergents alternately overshoot and undershoot its limit $x$ (in particular, knowing that $c_0 = \lfloor x \rfloor &lt; x$, the even convergents undershoot and the odd ones overshoot). So in particular, for all $n$, we have</p>
<!-- if it didn't, then x would either be above an odd convergent or below an even convergent c_n for some n. using the definition of the limit then, we can find an epsilon ε, such that for all N $|x - c_N| > ε$. say x is above an odd convergent c_N. then just let ε = |x - c_N|. not hard to show odd convergents are decreasing to the limit while evens are increasing -->
<center>
$\begin{align}
\frac{p_n}{q_n} &lt; x &lt; \frac{p_{n+1}}{q_{n+1}} \ \ \textrm{or} \ \  \frac{p_{n+1}}{q_{n+1}} &lt; x &lt; \frac{p_n}{q_n}
\end{align}$
</center>

<p>If we take the first case, then the first inequality gives $0 &lt; q_n x - p_n$ while the second one gives $q_{n+1} x - p_{n+1} &lt; 0$, so they&#39;re of opposing signs. Similarly the second case gives the same. $\blacksquare$</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>Claim:</strong> $r(q_n x - p_n)$ and $s(q_{n+1} x - p_{n+1})$ have the same signs.</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>Proof:</strong> This is just something you can check by cases. The opposing parity of $r,s$ and of $(q_n x - p_n), (q_{n+1} x - p_{n+1})$ cancel each other out. $\blacksquare$</p>
<p>Finally, putting this last fact to work, we get</p>
<center>
$\begin{align}
|bx - a| &amp; = |(r q_n + s q_{n+1})x - (r p_n + s p_{n+1})| \\
&amp; = |r(q_n x - p_n) + s(q_{n+1} x - p_{n+1})| \\
&amp; = |r||q_n x - p_n| + |s||q_{n+1} x - p_{n+1}| \\
&amp; &gt; |r||q_n x - p_n| \\
&amp; \geq |q_n x - p_n|
\end{align}$
</center>

<p>We can separate the absolute values in the 3rd equality since they have the same sign, and the last inequality comes from the fact that we showed the integer $r \geq 1$.</p>
<center>
$\blacksquare$
</center>

<p>For completeness sake,</p>
<p><strong>Corollary:</strong> Each convergent $c_n = \frac{p_n}{q_n}$ is a best rational approximation for $x$.</p>
<p><strong>Proof:</strong> Suppose otherwise, so that there $\exists \frac{a}{b}$ such that $b \leq q_n$ with</p>
<center>

$\begin{align}
\left| x - \frac{a}{b} \right| &lt; \left| x - \frac{p_n}{q_n} \right|
\end{align}$

</center>

<p>Multiplying these inequalities together gives</p>
<center>
$\begin{align}
|bx - a| &lt; |q_n x - p_n|
\end{align}$
</center>

<p>But this contradicts our theorem as $b \leq q_n &lt; q_{n+1}$. $\ \blacksquare$</p>
<!-- show that best rational approximations/convergents satisfy dirichlet's theorem -->
<h3 id="the-most-irrational-number">The Most Irrational Number</h3>
<p>If you want to approximate $\pi$, we now have a good way of doing so: take some convergent of the continued fraction. Looking at the first couple,</p>
<center>
$\begin{align}
\pi \approx c_0 &amp; = 3 \\
\pi \approx c_1 &amp; = 3 + \frac{1}{7} = \frac{22}{7} \approx 3.1429 \\
\pi \approx c_2 &amp; = 3 + \frac{1}{7 + \frac{1}{15}} = \frac{333}{106} \approx 3.141591
\end{align}$
</center>

<p>which are some of the more famous approximations of $\pi$. Note, if you do want to get really good approximations, making the last term in a convergent <em>large</em> is ideal. Notice how much closer we got with $c_2$ compared to $c_1$, and that is precisely because 15 is (relatively) much bigger than 7. These large coefficients get multiplicatively bigger as we simplify the convergent, giving us a rather large denominator $q_n$ that more finely dices the real numbers for us to approximate with. $\pi$ has a lot of these large numbers in its continued fraction expansion, giving us good convergents to create these surprisingly accurate best rational approximations.</p>
<center>

$\pi = [3; \color{red}{7}, \color{red}{15}, 1, \color{red}{292}, 1, 1, 1, 2, 1, 3, 1, \color{red}{14}, 2, 1, 1, 2, 2, 2, 2, ...]$

</center>

<p>This also means, if you care about small denominators, it&#39;s worth stopping <strong>one before a large number</strong> (i.e. at 7 instead of 15, or 1 instead of 292); if you need such a large number to generate a new best rational approximation (and get a really big denominator), then it must have been that the approximation <em>before</em> it must have also been really good if you had to zoom in that much on the next step.</p>
<hr>
<p><strong>NOTE:</strong> we proved that all convergents are rational approximations, but the converse is not true! $\frac{13}{4}$ is also a best rational approximation for $\pi$, but is not generated through our convergents.</p>
<hr>
<p>So, what if we minimize all the coefficients then? If we give no large numbers to stop at for our convergents, we&#39;ll be left with a number that is not easy to approximate at all. We know all the numbers are positive integers, so let&#39;s just set them all to 1 to minimize them:</p>
<center>

$1 +$ $\large{\frac{1}{1 + \frac{1}{1 + \frac{1}{1 + \frac{1}{\ddots}}}}}$

</center>

<p>We know this converges as we showed that the difference between consecutive convergents gets small (and so forms a Cauchy sequence), and as we saw before this is the Golden Ratio $\varphi$. We can also solve this directly if you wanted: if we set the value of the fraction to $x$</p>
<center>
$1 + \large{\frac{1}{ \fbox{$1 + \frac{1}{1 + \frac{1}{1 + \frac{1}{\ddots}}} $} }} = x$
</center>

<p>we can see that the boxed portion of the fraction is equivalent to the original, whole fraction, so we can substitute $x$ for the box.</p>
<center>
$1 + \frac{1}{x} = x$
<br>
$x^2-x-1=0$
</center>

<p>Is precisely the quadratic that has roots at $\frac{1 \pm \sqrt{5}}{2}$ (we only admit the positive solution by since all our convergents are positive, and limits preserve weak inequalities, so the limit is non-negative). </p>
<p>So if we look at some of the convergets of $\varphi$, they&#39;re quite bad at approximating it (for reference, $\varphi \approx 1.618034$):</p>
<center>
$\begin{align}
\varphi \approx c_0 &amp; = 1 \\
\varphi \approx c_1 &amp; = 1 + \frac{1}{1} = 2 \\
\varphi \approx c_2 &amp; = 1 + \frac{1}{1 + \frac{1}{1}} = \frac{3}{2} = 1.5 \\
\varphi \approx c_3 &amp; = 1 + \frac{1}{1 + \frac{1}{1 + \frac{1}{1}}} = \frac{5}{3} = 1.\overline{6} \\
\varphi \approx c_4 &amp; = 1 + \frac{1}{1 + \frac{1}{1 + \frac{1}{1 + \frac{1}{1}}}} = \frac{8}{5} = 1.6 \\
\end{align}$
</center>

<p>In fact, takes until $c_9$ to get 3 decimals correct. Remember, the <em>first</em> convergent for $\pi$ was already within 3 decimals.</p>
<center>

$\varphi \approx c_9 =$ $\large{\frac{89}{55}}$ $= 1.618\overline{18}$

</center>


<p>Since $\varphi$ is so bad—in fact as we&#39;ve demonstrated, the worst—to approximate rationally, it is often referred to as <strong>the most irrational number</strong>.</p>
<h2 id="relation-to-dirichlet-s-approximation-theorem">Relation to Dirichlet&#39;s Approximation Theorem</h2>
<p>Recall, in our first little discussion about approximating irrational numbers, we spoke about Dirichlet&#39;s Approximation Theorem.</p>
<p><strong>Dirichlet&#39;s Approximation Theorem:</strong> $\forall x \in \mathbb{R}$ and $\forall N \in \mathbb{N}$, there are integers $p$ and $q$ such that $0 &lt; q \leq N$ and $\left|qx - p \right| &lt; \frac{1}{N}$.</p>
<p>The more concrete result we got out of it was that we could have rational approximations $\frac{p}{q}$ that get us within $\frac{1}{q^2}$ of our irrational $x$, which is much better than our initial bound of being within $\frac{1}{2q}$ of $x$.</p>
<p>In our proof on the convergence of continued fractions, we actually say that our convergents actually satisfy this bound too. Look above in the proof, and we deduced that</p>
<center>

$\begin{align}\left| x - \frac{p_n}{q_n} \right| &lt; \frac{1}{q_{n+1} q_n} &lt; \frac{1}{q_n^2} \end{align}$

</center>

<p>and the final inequality comes from the fact that $q_{n+1} &gt; q_n$. So, as we&#39;d hope, our best rational approximations from continued fractions are also just outright good and efficient approximations.</p>
<p>In fact, we can usually do a little bit better.</p>
<p><strong>Corollary:</strong> For irrational $x$ and for all $n \in \mathbb{N}$, at least one of the convergents $\frac{p_n}{q_n}$ or $\frac{p_{n+1}}{q_{n+1}}$ satisfy the inequality</p>
<center>

$\begin{align}\left| x - \frac{p}{q} \right| &lt; \frac{1}{2q^2} \end{align}$

</center>

<p><strong>Proof:</strong> Suppose this isn&#39;t true. Then </p>
<center>

$\begin{align}
\frac{1}{2q_n^2} + \frac{1}{2q_{n+1}^2} \leq \left|x - \frac{p_n}{q_n} \right| + \left|x - \frac{p_{n+1}}{q_{n+1}}\right| = \left|\frac{p_n}{q_n} - \frac{p_{n+1}}{q_{n+1}}\right| = \frac{1}{q_n q_{n+1}}
\end{align}$

</center>

<p>The second equality follows since $\frac{p_n}{q_n} &lt; x &lt; \frac{p_{n+1}}{q_{n+1}}$ or $\frac{p_{n+1}}{q_{n+1}} &lt; x &lt; \frac{p_n}{q_n}$. Say we&#39;re in the first case, then </p>
<center>

$\begin{align}
\left|x - \frac{p_n}{q_n} \right| + \left|x - \frac{p_{n+1}}{q_{n+1}}\right| = \left(x - \frac{p_n}{q_n} \right) + \left(\frac{p_{n+1}}{q_{n+1}} - x \right)
\end{align}$

</center>

<p>and the $x$ terms cancel (similarly for the second case). The last equality is precisely the difference between two adjacent convergents we found earlier.</p>
<center>

$\begin{align}
\frac{1}{2q_n^2} + \frac{1}{2q_{n+1}^2} \leq \frac{1}{q_n q_{n+1}} \Rightarrow \frac{q_{n+1}^2 + q_n^2}{2q_n^2 q_{n+1}^2} \leq \frac{1}{q_n q_{n+1}} \Rightarrow (q_{n+1} - q_{n})^2 \leq 0
\end{align}$

</center>

<p>But we already know that $q_{n+1} &gt; q_n$, so this can&#39;t hold, giving us our contradiction. $ \ \blacksquare$</p>
<p>It turns out the converse to this is in fact true:</p>
<p><strong>Legendre&#39;s Theorem:</strong> If $x \in \mathbb{R}$, and $\frac{p}{q} \in \mathbb{Q}$ such that $\left| x - \frac{p}{q} \right| &lt; \frac{1}{2q^2}$, then $\frac{p}{q} = c_n$ is a convergent of the continued fraction for $x$.</p>
<p>We won&#39;t prove this, but the proof can be found on the <a href="https://en.wikipedia.org/wiki/Dirichlet%27s_approximation_theorem#Legendre&#39;s_theorem_on_continued_fractions">Wikipedia page</a>.</p>
<h2 id="finding-continued-fractions">Finding Continued Fractions</h2>
<p>One problem I had with continued fractions originally was that there didn&#39;t seem to be a particularly nice way of actually <em>finding</em> them. It&#39;s nice that we have this very straightforward way of doing it by separating integer parts and inverting the fractional, but that already requires us to have calculated the decimal expansion of whatever number we&#39;re expanding. This makes it seem not as elegant and a bit clunky, so when I found this <a href="https://www.ams.org/journals/mcom/1995-64-211/S0025-5718-1995-1297479-9/S0025-5718-1995-1297479-9.pdf">paper outlining another method</a>, I had to look through it.</p>
<p>The accuracy of this method will still rely on having some level of floating point precision, but otherwise, I think it is a much nicer of going about finding continued fractions in a way that weaves in another natural approximation method. The idea lies within finding roots of functions in a way similar to <a href="http://xperimex.com/blog/fixed-points/#newton-raphson-method">Newton&#39;s method</a>.</p>
<p>Say we want to find the continued fraction of the number $\alpha$. Further, assume that there is a twice differentiable function $f(x)$ such that $f(\alpha) = 0$. To get a rough idea of the algorithm, there are two facts we first must take note of.</p>
<hr>
<p><strong>1) The Mean Value Theorem:</strong> Given a function $f(x)$ that is differentiable on the interval $(a,b)$, the Mean Value Theorem states that $\exists c \in (a,b)$ such that</p>
<center>

$\begin{align} f&#39;(c) = \frac{f(b) - f(a)}{b-a} \end{align}$

</center>

<p>That is, there is a point that has a tangent with the same slope as the secant line between endpoints of the graph. So if we consider the interval between $(\alpha, t)$ where $f(\alpha) = 0$, we get that</p>
<center>

$\begin{align} f&#39;(c) = \frac{f(t) - f(\alpha)}{t - \alpha}  = \frac{f(t)}{t - \alpha}\end{align}$

</center>

<p>Rearranging a little bit and letting $t= \frac{p_n}{q_n}$ be a convergent of $\alpha$, we can see that </p>
<center>

$\begin{align} \left| \frac{p_n}{q_n} - \alpha \right| = \left| \frac{f(\frac{p_n}{q_n})}{f&#39;(c)} \right| \end{align}$

</center>

<p><strong>2) Relating convergents and remainder coefficients:</strong> Recall in our proof that simple infinite continued fractions converge, we found that </p>
<center>

$\begin{align} \left| \frac{p_n}{q_n} - a \right| = \frac{1}{ (\alpha_{n+1} q_n + q_{n-1})q_n } \end{align}$

</center>

<p>where $\alpha_{n+1}$ is the &quot;remainder&quot; coefficient we get when calculating continued fractions i.e.</p>
<center>

$\alpha = [a_0; a_1, a_2, \cdots, a_n, \alpha_{n+1}] = a_0 + \frac{1}{a_1 + \frac{1}{a_2 + \frac{1}{\frac{\ddots}{ a_n + \frac{1}{\alpha_{n+1}}}}}}$

</center>

<hr>
<p>If we combine these two equalities, we get that</p>
<center>

$\begin{align} \frac{1}{ (\alpha_{n+1} q_n + q_{n-1})q_n } = \left| \frac{p_n}{q_n} - a \right| = \left| \frac{f(\frac{p_n}{q_n})}{f&#39;(c)} \right| \end{align}$

</center>

<p>If we solve for $\alpha_{n+1}$:</p>
<center>

$\begin{align} \alpha_{n+1} = \frac{\left| f&#39;(c) \right|}{q_n^2 \left| f(\frac{p_n}{q_n} )\right|} - \frac{q_{n-1}}{q_n}  \end{align}$

</center>

<p>This is great, since now we have a direct way of computing the coefficients $a_{n+1} = \lfloor \alpha_{n+1} \rfloor$. Further, the computation <strong>only requires knowing the evaluating the function $f(x)$ and the previous two convergents</strong>! This is the basis for the algorithm: we repeatedly compute values of $a_{n+1}$ by computing the <em>remainder</em> $\alpha_{n+1}$ with our convergents.</p>
<p>However, this only maintains equality for the value fo $c \in (a, \frac{p_n}{q_n})$. So what we do instead is <em>approximate</em> $\alpha_{n+1}$ with a reasonably close value. One value that works just fine is $\frac{p_n}{q_n}$ itself. So what originally was could be a hard problem of finding decimal expansions of $\alpha$ to do our separate-and-invert algorithm, now becomes a much more tractable problem in computing decimals in evaluating a function. Also this process is memoryless: it does not need anything more than the previous state two convergents to compute the next. Whereas if we wanted to refine our continued fraction with the old method, we would have to start from the very beginning and recompute everything.</p>
<p>Again, this still requires calculating something else to an arbitrary precision to get the correct continued fraction (and we still need to get the first two convergents manually as seed values). So in the case of $\pi$, we are calculating instances of $\sin(x)$, which in some ways easier. This gives a wide range of numbers we can now compute continued fractions for:</p>
<ul>
<li>For $\sqrt{2}$, we use $f(x) = x^2 - 2$</li>
<li>For $\ln(n)$, we use $f(x) = e^x - n$.</li>
<li>For $\pi^2$, we use $f(x) = \sin(\sqrt{x})$</li>
<li>For $e^\pi$, we use $f(x) = \sin(\log x)$ </li>
</ul>
<p>Many other function compositions can lend to many other numbers that would seem otherwise hard to get continued fractions of.</p>
<p>For more details and a coded demo, check out this <a href="https://colab.research.google.com/drive/198WCWQF8zGwq_tJkPrkCLCNxDSoiU7lS?usp=sharing">Python notebook</a> that is set up to calculate the first 50 coefficients (as well as the convergents and their numerators and denominators) of the simple continued fraction for $\pi$.</p>
<h2 id="applications-of-best-rational-approximations">Applications of Best Rational Approximations</h2>
<h3 id="music-tuning">Music Tuning</h3>
<p>Approximating irrationals are convenient for nothing more than just that in most cases: convenience. But here&#39;s something that requires this irrational approximation.</p>
<p>We here sound and music intervals on an exponential scale. Given a note with frequency $f$, it&#39;s <strong>octave</strong> is the note with frequency $2f$. So obviously, they have a frequency ratio of 2:1. Since this, in a sense, is the simplest ratio we can have between notes&#39; frequencies, the octave forms the basic ratio for end points in our musical scale. The more interesting notes are the ones between an octave with more complex ratios to the base frequency. Common intervals include a major third with a frequence ratio of 6:5 to the base note, or perfect fourth with 4:3. But perhaps the most famous and most recognizable is the <strong>perfect fifth</strong> with a ratio of 3:2. The theme to <em>Star Wars</em> famously opens with a perfect fifth.</p>
<p>As nice as these rational intervals are, they pose a slightly annoying problem: they are not (geometrically) evenly spaced, so they don&#39;t divide an octave into even steps. If you wanted to build a piano, this would make tuning each note very tedious, and make our notes feel a bit random without this consistent spacing.</p>
<p>If we wanted to divide an octave evenly into $n$ notes, that means we want to be able to find the corresponding frequency ratio of $2^\frac{1}{n}$ (remember, we hear sound exponentially, so hearing the next note up is equivalent to multiplying our base frequency by our desired ratio). But this number is irrational (proof is identical to our why $\sqrt{2} = 2^\frac{1}{2}$ is irrational)! So this runs into a different problem: we&#39;ll never be able to exactly get our rational frequency ratios for our intervals like the fourth or the fifth.</p>
<p>So we&#39;re at a crossroads: either we keep our rational frequency ratios for nice intervals and the octave isn&#39;t evenly divided, or we divide our octave evenly and never have a rational interval. So we compromise: we find a value of $2^\frac{m}{n}$ that closely approximates our ratios, and that value of $n$ tells us how many notes we divide our octave into.</p>
<!-- note solving (3/2)^n = 2^m -> can 3^n = 2^(n+m) never has a solution by fundamental theorem of arithmetic -->
<p>Here&#39;s where we can use continued fractions and our best rational approximations. Since the perfect fifth is probably the most univerally harmonious interval, we&#39;ll try and approximate that first. Then, we note that </p>
<center>

$\begin{align} 2^{\log_2 (3/2)} = \frac{3}{2} \end{align}$

</center>

<p>So if we can approximate $\log_2 (3/2)$ the best we can, we&#39;ll get a reasonable rational exponent that closely solves $2^\frac{m}{n} = \frac{3}{2}$. We can write out the first few numbers of the continued fraction by hand using our algorithm from before:</p>
<center>

$\begin{align}
\log_2(\frac{3}{2}) = 0+\frac{1}{1+\frac{1}{1+\frac{1}{2+\frac{1}{2+\frac{1}{3+\frac{1}{\ddots}}}}}}
\end{align}$

</center>

<p>Looking at the first few convergents, we see that </p>
<center>
$\begin{align}
\log_2(\frac{3}{2}) &amp; = 0.584962500721 \ldots \\
&amp; \approx c_0 = 0 \\
&amp; \approx c_1 = 0 + \frac{1}{1} = 1 \\
&amp; \approx c_2 = 0 + \frac{1}{1 + \frac{1}{1}} = \frac{1}{2} = 0.5 \\
&amp; \approx c_3 = 0 + \frac{1}{1 + \frac{1}{1 + \frac{1}{2}}} = \frac{3}{5} = 0.6 \\
&amp; \approx c_4 = 0 + \frac{1}{1 + \frac{1}{1 + \frac{1}{2 + \frac{1}{2}}}} = \frac{7}{12} = 0.58\overline{3} \\
&amp; \approx c_5 = 0 + \frac{1}{1 + \frac{1}{1 + \frac{1}{2 + \frac{1}{2 + \frac{1}{3}}}}} = \frac{24}{41} = 0.\overline{58536} \\
\end{align}$
</center>

<p>Looking at our denominators, we get options of $n = 1,2,5,12,41,\cdots$. Using $n \leq 5$ gives too few notes in a scale, and $n = 41$ might be too many. So $n=12$ notes feels like a good in-between, and in fact is what we actually use on most pianos today: 7 white keys and 5 black per octave. (One interesting best approximation not found here is also $n=19$, which some might find a reasonable choice too)</p>
<!-- ## Finding Continued Fractions -->
<!-- quadratic have repeating continued fractions -->
<!-- https://www.ams.org/journals/mcom/1995-64-211/S0025-5718-1995-1297479-9/S0025-5718-1995-1297479-9.pdf -->
<h3 id="cryptography-and-wiener-s-attack">Cryptography and Wiener&#39;s Attack</h3>
<p><strong>RSA</strong> is one of the most widely used cryptographic protocols used, protecting most of the internet&#39;s traffic today.</p>
<p>Here&#39;s a brief rundown how two people, Alice and Bob, would share secret messages (i.e. can only be read by the recipient) using RSA:</p>
<ul>
<li>Bob chooses two (ideally large) prime numbers $p,q$ and calculates $N = pq$, and an integer $e$ (called the encryption exponent). He then releases to everyone the <strong>public key</strong> $(N, e)$. This is how people will hide and encode their messages to Bob.</li>
<li>To decrypt messages, we need we need the <strong>decryption exponent</strong> $d$ that satisfies $ed \equiv 1 \bmod \varphi(N)$. $\varphi(n)$ is <a href="https://en.wikipedia.org/wiki/Euler%27s_totient_function">Euler&#39;s totient function</a> and returns the total number of integers less than $n$ that are coprime to $n$. We also need $\gcd(e, \varphi(N)) = 1$.</li>
<li>The factorization of $N$ and $d$ are kept secret, and form the <strong>private key</strong>. This is what allows Bob and only Bob to decrypt messages.</li>
<li>To encrypt a message $M$, Alice sends the <strong>ciphertext</strong> $C = M^e \bmod N$</li>
<li>To decrypt it, Bob computes $C^d \equiv (M^e)^d \equiv M^{ed} \equiv M \bmod N$</li>
</ul>
<p>The decryption equivalence follows by Fermat&#39;s little theorem, and is not too hard to verify (you can also check the <a href="https://en.wikipedia.org/wiki/RSA_(cryptosystem">Wikipedia page</a>). Also, note that sometimes instead of $\varphi(n)$ people will also use the <a href="https://en.wikipedia.org/wiki/Carmichael_function">Carmichael function</a> $\lambda(n)$. In our case, $\lambda(pq) = \mathrm{lcm}(p-1,q-1) \leq (p-1)(q-1)$ which maintains all the properties needed.</p>
<p>The security of RSA relies on the surprising asymmetry in factorization: given $p$ and $q$, calculating $N = pq$ isn&#39;t hard, but given an $N$ finding two numbers such that $N = pq$ is difficult. Without being able to factor $N$, the private key remains private and hence messages can&#39;t be stolen. At least, that&#39;s our idea—it&#39;s secure because <i>we</i> don&#39;t know how to factor numbers efficiently (at least, not without <a href="https://en.wikipedia.org/wiki/Shor%27s_algorithm">quantum computers</a>). No one does. So we use RSA everywhere for that reason. </p>
<p>So if we could break it, that would be quite bad.</p>
<p><strong>Wiener&#39;s attack</strong> exploits one thing that we didn&#39;t put much effort specifying: the decryption exponent $d$. If $d$ is chosen in such a way that it&#39;s small enough (specifically when $d &lt; \frac{1}{3} N^{\frac{1}{4}}$) Wiener&#39;s attack can break through RSA. This, though, is a really small range of $d$. If we let $N$ be a number with 20 digits, $d$ can at most have 5 digits. </p>
<h4 id="some-preliminaries">Some Preliminaries</h4>
<hr>
<p><strong>First</strong>, note for (co)prime $p,q$, we have </p>
<center>
$\varphi(pq) = (p-1)(q-1) = pq - p - q + 1 = N - (p+q) + 1$. 
</center>

<p>This follows from a simple counting argument: the numbers that are <strong>not</strong> coprime to $pq$ are the multiples of $p$ and the multiples of $q$ less than $pq$, i.e. $1p, 2p, 3p, \cdots, (q-1)p$ and $1q,2q,3q,\cdots(p-1)q$. So there are $(p-1) + (q-1) = p + q - 2$ numbers not coprime to $pq$. There are $pq-1$ numbers less than $pq$. Hence there are </p>
<center>
$(pq - 1) - (p + q - 2) = pq - (p+q) + 1 = (p-1)(q-1)$ 
</center>

<p>numbers coprime to $pq$. (also follows because $\varphi$ is multiplicative, so $\varphi(pq) = \varphi(p)\varphi(q)$ if $p,q$ coprime; think Chinese Remainder Theorem).</p>
<p>So if we know $p+q$ then we know $\varphi(N)$ and vice versa. If you&#39;re familiar with Vieta&#39;s fomrulas, <strong>these look a lot like expressions that appear in quadratics</strong>:</p>
<center>
$(x-p)(x-q) = x^2 - (p+q)x + pq = x^2 - (N - \varphi(N) + 1)x + N$
</center>

<p>By the quadratic formula,</p>
<center>

$\begin{align} p,q = \frac{(N - \varphi(N) + 1) \pm \sqrt{(N - \varphi(N) + 1)^2 - 4(1)(N) }}{2(1)} \end{align}$

</center>

<p>So if we know $N$ and $\varphi(N)$, we can recover $p,q$ without ever needing to go through the problem of factoring. $N$ is already public information in RSA. To find $\varphi(N)$, all we know about $\varphi(N)$ is $ed \equiv 1 \bmod \varphi(N)$. In other words, $ed = 1 + k \cdot \varphi(N) = 1 + k \cdot (p-1)(q-1)$ for some integer $k$. Therefore,</p>
<center>

$\begin{align} \varphi(N) = \frac{ed - 1}{k} \end{align}$

</center>

<p>If we want to find $\varphi(N)$, what we really want to find is $k$ and $d$.</p>
<p></br></p>
<p><strong>Second</strong>, we make the following observation:</p>
<ul>
<li>Let $N=pq$, $e$, and $d$ be given.<!-- * Let $G = \gcd(pq)$. Then $\lambda(N) = \mathrm{lcm}(p-1, q-1) = \frac{(p-1)(q-1)}{G}$. The first equality follows from the Chinese Remainder Theorem, and the second is a standard equality between $\mathrm{lcm(\cdot)}$ and $\gcd(\cdot)$. --></li>
<li>Note $\varphi(N) = (p-1)(q-1)$.</li>
<li>Also, $ed = 1 + k \cdot \varphi(N) = 1 + k \cdot (p-1)(q-1)$ for some integer $k$</li>
<li>Dividing by $dpq$, we get $\frac{e}{pq} = \frac{k}{d} \cdot \frac{pq - p - q + 1 + \frac{1}{k}}{pq} = \frac{k}{d}(1-\delta)$ where $\delta = \frac{p + q - 1 - \frac{1}{k}}{pq}$</li>
<li>Note $\delta &lt; 1$ since $pq &gt; p+q$ for all $p,q &gt; 1$. So we get $\frac{e}{pq} &lt; \frac{k}{d}$ by a small amount.<!-- * $e$ and $pq = N$ are all public information, so we can use them to guess $\frac{k}{d}$ -->
</li>
</ul>
<p>So we have $\frac{e}{N} \approx \frac{k}{d}$, so if we can guess approximations (should start ringing a bell) of $\frac{e}{N}$, we might be able to guess $\frac{k}{d}$.</p>
<hr>
<p>Wiener&#39;s idea then is to use the convergents of the continued fraction for $\frac{e}{N}$ to get potential values of $\frac{k}{d}$, as those would give us nice rational approximations. </p>
<p><a href="https://en.wikipedia.org/wiki/Wiener%27s_attack"><strong>Example:</strong></a> Let $(N,e) = (90581, 17993)$ be our public key. </p>
<center>

$\begin{align} \frac{e}{N} = \frac{1}{5 + \frac{1}{29 + \frac{1}{\ddots + \frac{1}{3}}}} = [0; 5,2,29,4,1,3,2,4,3] \end{align}$

</center>

<p>The first convergent $\frac{0}{1}$ does not give $k,d$ values to factor $N$ ($k=0$ is the real problem). But it can be checked that the next convergent $\frac{1}{5} = \frac{k}{d}$ does work, and gives the correct guess for $\varphi(N)$:</p>
<center>

$\begin{align} \varphi(N) = \frac{17993 \cdot 5 - 1}{1} = 89964 \end{align}$

</center>

<p>If we plug this into our quadratic from before, we get $p,q = 379, 239$ which correctly factors $N$.</p>
<p>Here are all the conditions necessary for this attack.</p>
<p><strong>Wiener&#39;s theorem:</strong> Let $N=pq$ with $q &lt; p &lt; 2q$, and $d &lt; \frac{1}{3} N^{\frac{1}{4}}$ such that $ed \equiv 1 \bmod \varphi(N)$. Given $(N,e)$, one can recover $d$.</p>
<p><strong>Proof:</strong> First note that since $q&lt;p&lt;2q$, we have that $p+q - 1 &lt; 3\sqrt{pq}$:</p>
<center>

$(p+q-1)^2 &lt; (p+q)^2 &lt; (3q)^2 &lt; 9pq$

</center>

<p>Recall that $\varphi(N) = (p-1)(q-1) = N - p - q + 1$. Combining this with our above inequality gives $\left| N - \varphi(N) \right| &lt; 3\sqrt{pq} = 3\sqrt{N}$. Now also remember that $ed - k\varphi(N) = 1$, so we get that</p>
<center>

$\begin{align}
\left| \frac{e}{N} - \frac{k}{d} \right| &amp; = \left| \frac{ed - kN}{Nd} \right| \\
&amp; = \left| \frac{ed - k\varphi(N) - kN + k \varphi(N) }{Nd} \right| \\
&amp; = \left| \frac{1 - k(N - \varphi(N)) }{Nd} \right| \\
&amp; \leq \left| \frac{3k\sqrt{N} }{Nd} \right| \\
\end{align}$

</center>

<p>$k\varphi(N) = ed - 1 &lt; ed$, so since $e &lt; \varphi(N)$ (the public key can and usually is chosen as such because modular arithmetic ensures there is one), we then must have $k &lt; d$ for that equality to have any hope in working out. Therefore,</p>
<center>

$\begin{align}
\left| \frac{e}{N} - \frac{k}{d} \right| \leq \left| \frac{3k\sqrt{N} }{Nd} \right| &lt; \left| \frac{3d\sqrt{N} }{Nd} \right| = \left| \frac{3}{\sqrt{N}} \right| \\
\end{align}$

</center>

<p>Since $d &lt; \frac{1}{3} N^{\frac{1}{4}}$, we have that $9d^2 &lt; N^{\frac{1}{2}}$. Hence, </p>
<center>

$\begin{align}
\left| \frac{e}{N} - \frac{k}{d} \right| &lt; \left| \frac{3}{\sqrt{N}} \right| &lt; \left| \frac{3}{9d^2} \right| &lt; \frac{1}{2d^2} \\
\end{align}$

</center>

<p>By Legendre&#39;s theorem that we mentioned above, $\frac{k}{d}$ is equivalent to a convergent of the continued fraction for $\frac{e}{N}$. Also, $ed - k\varphi(N) = 1$, so $\gcd(k,d) = 1$, so $\frac{k}{d}$ is already in lowest terms. So not only is $\frac{k}{d}$ equivalent to a convergent, it is in fact the convergent with the same numerator and denominator.</p>
<center>
$\blacksquare$
</center>

<p>Note that the bound on $d &lt; \frac{1}{3}N^{\frac{1}{4}}$ was picked precisely to satisfy Legendre&#39;s theorem, to ensure it would be a convergent. Others have improved on this bound, and one we can clearly see that if we want $\frac{3}{\sqrt{N}} &lt; \frac{1}{2d^2}$, we can let $d &lt; \frac{1}{\sqrt{6}}N^{\frac{1}{4}}$.</p>
<h3 id="solving-pell-s-equation">Solving Pell&#39;s Equation</h3>
<p>Pell&#39;s equation is the <a href="https://en.wikipedia.org/wiki/Diophantine_equation#">Diophantine equation</a> (that is, we want integer solutions for it)</p>
<center>
$x^2 - Dy^2 = 1$
</center>

<p>where $D$ is a non-square positive integer (for negative or perfect square $D$ since there are only the finitely many solutions $(\pm 1, 0)$ by considering the sign of the equation or factoring a difference of squares). Continued fractions and solutions to Pell&#39;s equations are surprisingly intertwined. </p>
<p>The key lies in the fact that there is a 1-to-1 correspondence between <strong>quadratic irrationals</strong> and repeating continued fractions. That is, if the coefficients in a continued fraction ever cycle, then the continued fraction can be written as $\frac{p + \sqrt{q}}{r}$ where $q$ is a non-square. </p>
<p>We won&#39;t get into it here, but here are some <a href="https://sites.millersville.edu/bikenaga/number-theory/periodic-continued-fractions/periodic-continued-fractions.html">notes</a> and a <a href="https://math.uchicago.edu/~may/VIGRE/VIGRE2008/REUPapers/Yang.pdf">paper</a> that fill in the details for quadratic irrationals and Pell&#39;s equation.</p>
<p>Pell&#39;s equation seems innocuous at first—just a genereic equation that people historically studied for one reason or another, but it is because of its general form that lends itself to the necessity of studying Pell&#39;s equation.</p>
<p><strong>Question:</strong> The <em>triangular numbers</em> are $1, 3, 6, 10, \cdots, \frac{n(n+1)}{2}, \cdots $. Are any of these a perfect square?</p>
<p><img src="/img/pi-irrational/triangular_numbers.png"></p>
<center style="color: #666;">
<p>The first 6 triangular numbers. Credit: Wikipedia</p>
</center>

<p><strong>Solution:</strong> We are essentially solving $\frac{1}{2}n(n+1) = m^2$. Rewriting a little bit, we want to solve $(2n+1)^2 - 8m^2 = 1$. Let $x = 2n+1$ and $y = m$, we just need to find solutions to $x^2 - 8y^2 =1$. From the above results (that we did not cover), we can do that systematically with the continued fraction for $\sqrt{8}$.</p>
<hr>
<p>For an absurd historical example of Pell&#39;s equation, here&#39;s <a href="https://en.wikipedia.org/wiki/Archimedes%27s_cattle_problem">one attributed to Archimedes</a>. </p>
<h2 id="the-original-proof-of-the-irrationality-of-pi-">The Original Proof of the Irrationality of $\pi$</h2>
<p>We&#39;ve gone through a few properties and interesting tidbits that characterize irrational numbers especially as it comes to computing and approximating them. These tools, especially of continued fractions, give a tool that can be used to deduce irrationality of numbers. In fact, the first proofs that $e$ and $\pi$ were irrational originally came from them. But I wanted to talk about them specifically because I want it to be clear jsut how little we actually know of irrational numbers and how difficult it can actually be to show that numbers are irrational (as we&#39;ll discuss below). Continued fractions, though, seem to be a more universal way out. We&#39;ve already shown how $\sqrt{2}$ is irrational, but the actual proof is quite unique; we didn&#39;t use any of the characteristics of irrational numbers. But then we showed it was irrational again purely from its continued fraction, and that almost completely streamlined the proof to not only be direct, but essentially shorten the proof to one line: just show the continued fraction. </p>
<p>Before we go onto some of the more modern proofs $\pi$ is irrational, we&#39;re now somewhat familiar with continued fractions, so let&#39;s look at J. H. Lambert&#39;s (1761) original proof using them.</p>
<!-- show lambert's original proof -->
<p><strong>Theorem: $\pi$ is irrational.</strong></p>
<p><strong>Proof:</strong> I&#39;m adapting the proof found on this <a href="https://math.stackexchange.com/questions/895611/lamberts-original-proof-that-pi-is-irrational">Stack Exchange post</a>, as it only uses what&#39;s necessary. For some more rigor, the <a href="https://en.wikipedia.org/wiki/Proof_that_%CF%80_is_irrational#Laczkovich&#39;s_proof">Wikipedia page</a> or this <a href="https://www.jstor.org/stable/2974737">paper</a> provide good details.</p>
<p>There are a few steps we&#39;ll take along the way.</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>Step 1:</strong> A continued fraction for $\tan(x)$.</p>
<p>This is by far the most tedious step, and I&#39;ll only sketch it out for actually how annoying it is. The way to derive it is to essentially consider the quotient of the power series for $\sin(x)$ and $\cos(x)$.</p>
<center>

$\begin{align}
\tan(x) = \frac{\sin(x)}{\cos(x)} = \frac{\sum_{n=0}^{\infty} (-1)^n \frac{x^{2n+1}}{(2n+1)!}}{\sum_{n=0}^{\infty} (-1)^n \frac{x^{2n}}{(2n)!}} = \frac{x - \frac{x^3}{3!} + \frac{x^5}{5!} - \frac{x^7}{7!} + \cdots}{1 - \frac{x^2}{2!} + \frac{x^4}{4!} - \frac{x^6}{6!} + \cdots}
\end{align}$

</center>

<p>We&#39;ll now do a series of manipulations on this last fraction:</p>
<center>

$\begin{align}
\frac{x - \frac{x^3}{3!} + \frac{x^5}{5!} - \frac{x^7}{7!} + \cdots}{1 - \frac{x^2}{2!} + \frac{x^4}{4!} - \frac{x^6}{6!} + \cdots} &amp; = x \cdot \frac{1 - \frac{x^2}{3!} + \frac{x^4}{5!} - \frac{x^6}{7!} + \cdots}{1 - \frac{x^2}{2!} + \frac{x^4}{4!} - \frac{x^6}{6!} + \cdots} \\

&amp; = x \cdot \frac{1}{\frac{1 - \frac{x^2}{2!} + \frac{x^4}{4!} - \frac{x^6}{6!} + \cdots}{1 - \frac{x^2}{3!} + \frac{x^4}{5!} - \frac{x^6}{7!} + \cdots}} 
\end{align}$

</center>

<p>Let&#39;s look at the new sub-fraction of power series we have in the denominator. We&#39;ll now add and subtract the denominator of the sub-fraction as a special form of 0 to its numerator:</p>
<center>

$\begin{align}

% \frac{1 - \frac{x^2}{2!} + \frac{x^4}{4!} - \frac{x^6}{6!} + \cdots}{1 - \frac{x^2}{3!} + \frac{x^4}{5!} - \frac{x^6}{7!} + \cdots} &amp; = \frac{1 - \frac{x^2}{2!} + \frac{x^4}{4!} - \frac{x^6}{6!} + \cdots + (1 - \frac{x^2}{3!} + \frac{x^4}{5!} - \frac{x^6}{7!} + \cdots) - (1 - \frac{x^2}{3!} + \frac{x^4}{5!} - \frac{x^6}{7!} + \cdots)}{1 - \frac{x^2}{3!} + \frac{x^4}{5!} - \frac{x^6}{7!} + \cdots}

\frac{\color{red}{1 - \frac{x^2}{2!} + \frac{x^4}{4!} - \frac{x^6}{6!} + \cdots} + \overset{= \ 0}{\overline{(1 - \frac{x^2}{3!} + \frac{x^4}{5!} - \frac{x^6}{7!} + \cdots) \color{red}{- (1 - \frac{x^2}{3!} + \frac{x^4}{5!} - \frac{x^6}{7!} + \cdots)}}}}{1 - \frac{x^2}{3!} + \frac{x^4}{5!} - \frac{x^6}{7!} + \cdots}

\end{align}$

</center>

<p>Combining the terms in <span style="color:red">red</span>:</p>
<center>

$\begin{align}

\frac{(1 - \frac{x^2}{3!} + \frac{x^4}{5!} - \frac{x^6}{7!} + \cdots) \color{red}{- \frac{2x^2}{3!} + \frac{4x^4}{5!} - \frac{6x^6}{7!} + \cdots}}{1 - \frac{x^2}{3!} + \frac{x^4}{5!} - \frac{x^6}{7!} + \cdots} &amp; = 1 + \frac{\color{red}{- \frac{2x^2}{3!} + \frac{4x^4}{5!} - \frac{6x^6}{7!} + \cdots}}{1 - \frac{x^2}{3!} + \frac{x^4}{5!} - \frac{x^6}{7!} + \cdots} \\

&amp; = 1 - x^2 \cdot \frac{\color{red}{\frac{2}{3!} - \frac{4x^2}{5!} + \frac{6x^4}{7!} - \cdots}}{1 - \frac{x^2}{3!} + \frac{x^4}{5!} - \frac{x^6}{7!} + \cdots} \\

&amp; = 1 - x^2 \cdot \frac{\color{red}{\frac{1}{3} - \frac{x^2}{3!} \frac{1}{5} + \frac{x^4}{5!} \frac{1}{7} - \cdots}}{1 - \frac{x^2}{3!} + \frac{x^4}{5!} - \frac{x^6}{7!} + \cdots} \\

\end{align}$

</center>

<p>So, currently, we have </p>
<center>

$\begin{align}

\tan(x) &amp; = x \cdot \frac{1}{\frac{1 - \frac{x^2}{2!} + \frac{x^4}{4!} - \frac{x^6}{6!} + \cdots}{1 - \frac{x^2}{3!} + \frac{x^4}{5!} - \frac{x^6}{7!} + \cdots}} \\

&amp; = \frac{x}{1 - x^2 \cdot \frac{\frac{1}{3} - \frac{x^2}{3!} \frac{1}{5} + \frac{x^4}{5!} \frac{1}{7} - \cdots}{1 - \frac{x^2}{3!} + \frac{x^4}{5!} - \frac{x^6}{7!} + \cdots}} \\

&amp; = \frac{x}{1 - \frac{x^2}{\frac{1 - \frac{x^2}{3!} + \frac{x^4}{5!} - \frac{x^6}{7!} + \cdots}{\frac{1}{3} - \frac{x^2}{3!} \frac{1}{5} + \frac{x^4}{5!} \frac{1}{7} - \cdots}}}

\end{align}$

</center>

<p>We can then continue to play the same game and adding and subtracting the denominator of our sub-fraction to its numerator:</p>
<center>

$\begin{align}

\frac{\color{red}{1 - \frac{x^2}{3!} + \frac{x^4}{5!} - \frac{x^6}{7!} + \cdots} + 3(\frac{1}{3} - \frac{x^2}{3!} \frac{1}{5} + \frac{x^4}{5!} \frac{1}{7} - \cdots) \color{red}{- 3(\frac{1}{3} - \frac{x^2}{3!} \frac{1}{5} + \frac{x^4}{5!} \frac{1}{7} - \cdots)}}{\frac{1}{3} - \frac{x^2}{3!} \frac{1}{5} + \frac{x^4}{5!} \frac{1}{7} - \cdots}

\end{align}$

</center>

<p>We multiplied them by 3 to clear the units. Combining the terms in <span style="color:red">red</span> again:</p>
<center>

$\begin{align}

\frac{3(\frac{1}{3} - \frac{x^2}{3!} \frac{1}{5} + \frac{x^4}{5!} \frac{1}{7} - \cdots) \color{red}{- \frac{x^2}{3!} \frac{2}{5} + \frac{x^4}{5!} \frac{4}{7} - \cdots}}{\frac{1}{3} - \frac{x^2}{3!} \frac{1}{5} + \frac{x^4}{5!} \frac{1}{7} - \cdots} &amp; = 3 - x^2 \cdot \frac{\color{red}{\frac{1}{3} \frac{1}{5} - \frac{x^2}{3!} \frac{1}{5 \cdot 7} + \cdots}}{\frac{1}{3} - \frac{x^2}{3!} \frac{1}{5} + \frac{x^4}{5!} \frac{1}{7} - \cdots} 

\end{align}$

</center>

<p>So then our expansion is</p>
<center>

$\begin{align}

\tan(x) &amp; = \frac{x}{1 - \frac{x^2}{\frac{1 - \frac{x^2}{3!} + \frac{x^4}{5!} - \frac{x^6}{7!} + \cdots}{\frac{1}{3} - \frac{x^2}{3!} \frac{1}{5} + \frac{x^4}{5!} \frac{1}{7} - \cdots}}} \\

&amp; = \frac{x}{1 - \frac{x^2}{3 - x^2 \cdot \frac{\frac{1}{3} \frac{1}{5} - \frac{x^2}{3!} \frac{1}{5 \cdot 7} + \cdots}{\frac{1}{3} - \frac{x^2}{3!} \frac{1}{5} + \frac{x^4}{5!} \frac{1}{7} - \cdots} }} \\

&amp; = \frac{x}{1 - \frac{x^2}{3 - \frac{x^2}{\frac{\frac{1}{3} - \frac{x^2}{3!} \frac{1}{5} + \frac{x^4}{5!} \frac{1}{7} - \cdots}{\frac{1}{3} \frac{1}{5} - \frac{x^2}{3!} \frac{1}{5 \cdot 7} + \cdots} }}} \\

\end{align}$

</center>

<p>If we continue doing this, we see the pattern</p>
<center>

$\begin{align}

\tan(x) &amp; = \frac{x}{1 - \frac{x^2}{3 - \frac{x^2}{ 5 - \frac{x^2}{7 - \frac{x^2}{\ddots}} }}} \\

\end{align}$

</center>

<p>Obviously, this isn&#39;t fully rigorous as we&#39;re playing with infinite series pretty carelessly, so see the above links for more details.</p>
<!-- On Lambert's Proof of the Irrationality of π Author(s): M. Laczkovich -->
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>Step 2:</strong> A condition for irrationality.</p>
<p><strong>Lemma:</strong> For a continued fraction</p>
<center>
$\begin{align}
\frac{a_1}{b_1 - \frac{a_2}{b_2 - \frac{a_3}{b_3 - \frac{a_4}{b_4 - \frac{a_5}{\ddots}} }}} \\
\end{align}$
</center>

<p>assume that $1 + a_n \leq b_n$. If $1+a_n &lt; b_n$ infinitely often, then the fraction is irrational.</p>
<p><strong>Proof:</strong> For contradiction, say it is rational.</p>
<center>
$\begin{align}
\frac{\lambda_1}{\lambda_0} = \frac{a_1}{b_1 - \frac{a_2}{b_2 - \frac{a_3}{b_3 - \frac{a_4}{b_4 - \frac{a_5}{\ddots}} }}} \\
\end{align}$
</center>

<p>The conditions $1 + a_n \leq b_n$ and $1+a_n &lt; b_n$ infinitely often ensure that our continued fraction is between 0 and 1 (analyze the convergents), so we have $\lambda_1 &lt; \lambda_0$. To make our life simpler, let&#39;s call a lower portion of the fraction $\rho_1$:</p>
<center>
$\begin{align}
\rho_1 = \frac{a_2}{b_2 - \frac{a_3}{b_3 - \frac{a_4}{b_4 - \frac{a_5}{\ddots}} }} \\
\end{align}$
</center>

<p>Then we have</p>
<center>
$\begin{align}
\frac{\lambda_1}{\lambda_0} = \frac{a_1}{b_1 - \rho_1} \Rightarrow \rho_1 = \frac{b_1 \lambda_1 - a_1 \lambda_0}{\lambda_1}
\end{align}$
</center>

<p>So $\rho_1 = \frac{\lambda_2}{\lambda_1}$ is rational. But also, since $\rho_1$ is essentially the same &quot;type&quot; of continued fraction as the original, it too is between 0 and 1. Hence $\rho_1 &lt; 1$ and therefore $\lambda_2 &lt; \lambda_1$. We can keep repeating this process, producing a sequence of strictly descending positive integers $\cdots &lt; \lambda_2 &lt; \lambda_1 &lt; \lambda_0$. But clearly this is impossible! So our continued fraction is irrational. $\ \blacksquare$</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>Step 3:</strong> Showing $\pi$ is irrational.</p>
<p>Say $\pi$ is rational. Then $\frac{\pi}{4} = \frac{a}{b}$ is also rational, and $\tan(\frac{\pi}{4}) = 1$. But we also have our continued fraction for $\tan(x)$ :</p>
<center>

$\begin{align}

\tan(\frac{\pi}{4}) &amp; = \tan(\frac{a}{b}) = \frac{\frac{a}{b}}{1 - \frac{(\frac{a}{b})^2}{3 - \frac{(\frac{a}{b})^2}{ 5 - \frac{(\frac{a}{b})^2}{7 - \frac{(\frac{a}{b})^2}{\ddots}} }}} = \frac{a}{1b - \frac{a^2}{3b - \frac{a^2}{ 5b - \frac{a^2}{7b - \frac{a^2}{\ddots}} }}}

\end{align}$

</center>

<p>But clearly, $a^2$ is constant, so for a large enough $n$, we&#39;ll have $1 + a^2 &lt; nb$. So at some point, we&#39;ll have a sub-fraction</p>
<center>

$\begin{align}

\frac{a^2}{(2n+1)b - \frac{a^2}{(2n+3)b - \frac{a^2}{ (2n+5)b - \frac{a^2}{(2n+7)b - \frac{a^2}{\ddots}} }}}

\end{align}$

</center>

<p>that satisfies our <strong>Step 2</strong> claim, and hence is irrational. If that subfraction is irrational, then clearly the whole fraction is irrational (just by thinking about how that continued fraction would collapse and simplify up). But clearly $\tan(\frac{\pi}{4}) = 1$ is rational. Contradiction!</p>
<p>So it must be that $\pi$ is irrational.</p>
<center>
$\blacksquare$
</center>

<p>In case you were interested, since we spent all that time with approximation theorems from before, it&#39;s interesting to note that for all integers $p,q$ we have</p>
<center>

$\large \left|\pi - \frac{p}{q} \right|$ $ &gt; \large \frac{1}{q^{42}}$

</center>

<p>so $\pi$ gets <em>pretty close</em> to some rational numbers (as we&#39;ve seen with our convergents before), but it&#39;s interesting seeing the lower bound given. As always, <a href="https://www.elibm.org/ft/10012144000">paper attached</a>.</p>
<!-- constructive proof of π irrational: https://www.elibm.org/ft/10012144000 -->
<!-- gives alternate proof π is irrational -->
<h2 id="the-simpler-irrationality-proofs">The Simpler Irrationality Proofs</h2>
<p>This proof is important for its history alone: it was the first sound proof that $\pi$ is irrational. In fact, $e$ was also first proven irrational in a similar way (Euler, 1737) by writing out the <a href="http://www-fourier.ujf-grenoble.fr/~marin/une_autre_crypto/articles_et_extraits_livres/Cohn_H_A_Short_proof_of_the_simple_convergent_of_e.pdf">continued fraction for $e$ and showing it was infinite</a>. </p>
<p>But Fourier had a much better proof that $e$ is irrational:</p>
<!-- show fourier's proof for e, and lead into the more general proofs -->
<p><strong>Claim: $e$ is irrational.</strong></p>
<p><strong>Proof:</strong> Suppose $e = \frac{a}{N}$ was rational. Now consider $e\cdot N!$  which is clearly an integer by assuming $e = \frac{a}{N}$. We can evaluate this using the series expansion $e = \sum_{k=0}^\infty \frac{1}{k!}$.</p>
<center>

$\begin{align}

e \cdot N! &amp; = \frac{N!}{0!} + \frac{N!}{1!} + \cdots + \frac{N!}{(N-1)!} + \frac{N!}{N!} + \frac{N!}{(N+1)!} + \frac{N!}{(N+2)!} + \cdots \\
&amp; = \color{blue}{N! + N! + \frac{N!}{2!} + \cdots + N + 1} + \color{red}{\frac{1}{N+1} + \frac{1}{(N+1)(N+2)} + \cdots}

\end{align}$

</center>

<p>Now the terms in <span style="color:blue">blue</span> clearly add to an integer. But the parts in <span style="color:red">red</span>:</p>
<center>

<!-- ${\scriptsize 
\begin{align}

\frac{1}{N+1} + \frac{1}{(N+1)(N+2)} + \frac{1}{(N+1)(N+2)(N+3)} + \cdots & = \frac{1}{N+1}(1 + \frac{1}{(N+2)} + \frac{1}{(N+2)(N+3)} + \cdots) \\\

& < \frac{1}{N+1}(1 + \frac{1}{(N+2)} + \frac{1}{(N+2)(N+2)} + \cdots) \\\

& = \frac{1}{N+1} \cdot \frac{1}{1-\frac{1}{N+2}} \\\
& = \frac{1}{N+1} \cdot \frac{N+2}{N+1} < 1

\end{align}
}$ -->

${\scriptsize 
\begin{align}

\frac{1}{N+1} + \frac{1}{(N+1)(N+2)} + \frac{1}{(N+1)(N+2)(N+3)} + \cdots &amp; &lt; \frac{1}{N+1} + \frac{1}{(N+1)(N+1)} + \frac{1}{(N+1)(N+1)(N+1)} + \cdots \\
&amp; = \frac{1}{N+1} \cdot \frac{1}{1 - \frac{1}{N+1}} \\
&amp; = \frac{1}{N+1} \cdot \frac{N+1}{N} \\
&amp; = \frac{1}{N} &lt; 1


\end{align}
}$


<!-- $\frac{1}{N+1} + \frac{1}{(N+1)(N+2)} + \frac{1}{(N+1)(N+2)(N+3)} + \cdots = \frac{1}{(N+1)}(1 + \frac{1}{(N+2)} + \frac{1}{(N+2)(N+3)} + \cdots)$ -->

</center>

<p>We bounded the <span style="color:red">red</span> series by a geometric series, and were able to show that it must be less than 1. But that means the series in red is <em>not</em> an integer. Therein lies our contradiction: if we assume $e$ is rational, we have $e \cdot N!$ must be an integer, but the series expansion for $e$ would suggest that it&#39;s not.</p>
<center>

$\begin{align}

e \cdot N! &amp; = \overset{\in \mathbb{Z}}{\overline{\color{blue}{N! + N! + \frac{N!}{2!} + \cdots + N + 1}}} + \overset{\notin \mathbb{Z}}{\overline{\color{red}{\frac{1}{N+1} + \frac{1}{(N+1)(N+2)} + \cdots}}} \notin \mathbb{Z}

\end{align}$

</center>



<center>
$\blacksquare$
</center>

<hr>
<p>Continued fractions are still useful today, but for irrationality proofs, the above is so much more attractive compared to finding infinite continued fractions. Which makes me want to think that Lambert&#39;s proof that $\pi$ is irrational—albeit important—is an unwieldy relic to what else is there. </p>
<p><strong>Claim:</strong> $\pi$ is irrational.</p>
<p>I. Niven&#39;s (1947) proof that $\pi$ is irrational is actually quite short, and only relies on some calculus and a helper function. Notably, the key fact that it relies on is that $\pi$ is the smallest positive 0 of $\sin(x)$.</p>
<p><strong>Lemma:</strong> For all $n \geq 1$, consider the function </p>
<center>

$\begin{align} f(x) = \frac{x^n(a-bx)^n}{n!} \end{align}$

</center>

<p>Then the following are true:</p>
<ol>
<li>$f(x)$ is a polynomial of the form $\frac{1}{n!} \sum_{k=n}^{2n} c_k x^k$ with integer coefficients $c_k$</li>
<li>For $0 &lt; x &lt; \frac{a}{b}$, we have $0 &lt; f(x) &lt; \frac{1}{n!}$</li>
<li>For all $k \geq 0$, the derivatives $f^{(k)}(0)$ and $f^{(k)}(\frac{a}{b})$ are integers.</li>
</ol>
<p><strong>Proof:</strong> Claims 1. and 2. are straightforward (consider binomial expansion, and the factors in the numerator). For 3., note by 1., we&#39;ve shown $f(x)$ is a polynomial consisting of terms with degree between $n$ and $2n$. So $f^{(k)}(0) = 0$ unless $n\leq k\leq 2n$. When $n\leq k\leq 2n$, then $f^{(k)}(0) = \frac{k!}{n!} c_k$. Since $k \geq n$ and $c_k$ is an integer, then $\frac{k!}{n!} c_k$ is also an integer. By the symmetry in $f(x) = f(\frac{a}{b}-x)$, we get $f^{(k)}(x) = (-1)^k f^{(k)}(\frac{a}{b}-x)$. Therefore $f^{(k)}(\frac{a}{b}) = (-1)^k f^{(k)}(0)$ is also an integer. $ \ \blacksquare$</p>
<p>Now we can prove $\pi$ is irrational.</p>
<p><strong>Proof:</strong> Assume $\pi = \frac{a}{b}$ is rational, and consider $f(x)$ from the above lemma. Now define the new function</p>
<center>

$F(x) = f(x) - f^{(2)}(x) + f^{(4)}(x) - \cdots + (-1)^n f^{(2n)}(x)$

</center>

<p>If we take the derivative of this, we find</p>
<center>

$\begin{align}
F&#39;(x) &amp; = f^{(1)}(x) - f^{(3)}(x) + f^{(5)}(x) - \cdots + (-1)^n f^{(2n+1)}(x) \\
F&#39;&#39;(x) &amp; = f^{(2)}(x) - f^{(4)}(x) + f^{(6)}(x) - \cdots + (-1)^n f^{(2n+2)}(x) \\
\end{align}$

</center>

<p>$F&#39;&#39;(x)$ looks a lot like $F(x)$. In particular, we have this relation:</p>
<center>

$\begin{align}
-F&#39;&#39;(x) + f(x) &amp; = F(x) \\
\end{align}$

</center>

<p>Note this holds precisely because $f^{(2n+2)}(x) = 0$. With this in mind, we can see that the following derivative is</p>
<center>

$\begin{align}
\frac{\mathrm{d}}{\mathrm{d}x} \left( F&#39;(x)\sin(x) - F(x)\cos(x) \right) = F&#39;&#39;(x) \sin(x) + F(x) \sin(x) = f(x)\sin(x)
\end{align}$

</center>

<p>Thus, if we integrate the righthand-side,</p>
<center>

$\begin{align}
\int_{0}^{\pi} f(x)\sin(x) \ dx = \left[ F&#39;(x)\sin(x) - F(x)\cos(x) \right]_{0}^{\pi} = F(\pi) + F(0)
\end{align}$

</center>

<p>By part 3. of our lemma $f^{(k)}(\pi)$ and $f^{(k)}(0)$ are integers for all $k$, so $F(\pi) + F(0)$ is an integer. </p>
<p>Note now for $0&lt;x&lt;\pi = \frac{a}{b}$ and that $0 &lt; \sin(x) &lt; 1$ in this range, we have</p>
<center>

$\begin{align}
0 &lt; f(x) \sin(x) = \frac{x^n(a-bx)^n}{n!} \sin(x) = \frac{x^n a^n (1-\frac{b}{a}x)^n}{n!} \sin(x) &lt; \frac{\pi^n a^n}{n!}
\end{align}$

</center>

<p>But the RHS can be made arbitrarily small, i.e. $\frac{\pi^n a^n}{n!} &lt; \frac{1}{\pi}$ for a big enough $n$. So we can bound our integral by </p>
<center>

$\begin{align}
0 &lt; \int_{0}^{\pi} f(x)\sin(x) \ dx &lt; \pi \cdot \frac{\pi^n a^n}{n!} &lt; 1
\end{align}$

</center>

<p>However, we claimed that $\int_{0}^{\pi} f(x)\sin(x) = F(\pi) + F(0)$ is an integer. But there is no integer between 0 and 1! So our assumption that $\pi$ was rational must be wrong, and so $\pi$ is irrational.</p>
<center>

$\blacksquare$

</center>

<p>This proof is &quot;simpler&quot; in that the mathematical machinery required is relatively low-level. It might be that the actual contradiction we were looking for is less obvious, but we didn&#39;t have to prove that many obscure, auxilliary lemmas like we did with continued fractions in Lambert&#39;s proof.</p>
<hr>
<p><a href="https://link.springer.com/book/10.1007/978-3-662-57265-8"><em>Proofs from THE BOOK</em></a> generalizes this proof strategy to show a few more interesting irrationality results.</p>
<p><strong>Lemma:</strong> For all $n \geq 1$, consider the function </p>
<center>

$\begin{align} f(x) = \frac{x^n(1-x)^n}{n!} \end{align}$

</center>


<p>Then the following are true:</p>
<ol>
<li>$f(x)$ is a polynomial of the form $\frac{1}{n!} \sum_{k=n}^{2n} c_k x^k$ with integer coefficients $c_k$</li>
<li>For $0 &lt; x &lt; 1$, we have $0 &lt; f(x) &lt; \frac{1}{n!}$</li>
<li>For all $k \geq 0$, the derivatives $f^{(k)}(0)$ and $f^{(k)}(1)$ are integers.</li>
</ol>
<!-- **Proof:** Claims 1. and 2. are straightforward (consider binomial expansion, and the factors in the numerator). For 3., note by 1., we've shown $f(x)$ is a polynomial consisting of terms with degree between $n$ and $2n$. So $f^{(k)}(0) = 0$ unless $n\leq k\leq 2n$. When $n\leq k\leq 2n$, then $f^{(k)}(0) = \frac{k!}{n!} c_k$. Since $k \geq n$ and $c_k$ is an integer, then $\frac{k!}{n!} c_k$ is also an integer. By the symmetry in $f(x) = f(1-x)$, we get $f^{(k)}(x) = (-1)^k f^{(k)}(1-x)$. Therefore $f^{(k)}(1) = (-1)^k f^{(k)}(0)$ is also an integer. -->
<p>Proof follows exactly as you&#39;d expect from before.</p>
<p><strong>Theorem:</strong> $e^r$ is irrational for all rational $r \neq 0$.</p>
<p><strong>Proof:</strong> We can reduce this by considering $e^p$ is irratraional for all <em>integers</em> $p$, since if $e^{\frac{p}{q}}$ was rational, then $(e^{\frac{p}{q}})^q = e^p$ would also be rational. The key idea here is using that $\frac{\mathrm{d}}{\mathrm{d}x} e^x = e^x$.</p>
<p>Let $f(x) = \frac{x^n(1-x)^n}{n!}$ refer to the one from the lemma above. As usual, assume the contrary and that $e^p = \frac{a}{b}$. Now consider the new function</p>
<center>

$F(x) = p^{2n} f(x) - p^{2n-1}f&#39;(x) + p^{2n-2}f&#39;&#39;(x) \mp \cdots + f^{(2n)}(x)$

</center>

<p>This looks familiar to the one Niven used to show $\pi$ is irrational. Taking its derivative:</p>
<center>

$F&#39;(x) = p^{2n} f&#39;(x) - p^{2n-1}f&#39;&#39;(x) + p^{2n-2}f&#39;&#39;(x) \mp \cdots + f^{(2n+1)}(x)$

</center>

<p>Hence, we get the relation</p>
<center>

$-\frac{1}{p}F&#39;(x) + p^{2n} f(x) = F(x)$

</center>

<p>Now we take the derivative of a particularly nice function:</p>
<center>

$\begin{align}
\frac{\mathrm{d}}{\mathrm{d}x}(e^{px} F(x)) = pe^{px}F(x) + e^{px}F&#39;(x) = p^{2n+1}e^{px} f(x)
\end{align}$

</center>

<p>Integrating, we then get</p>
<center>

$\begin{align}
\int_{0}^{1} p^{2n+1}e^{px} f(x) \ dx = \left[  e^{px} F(x) \right]_{0}^{1} = e^p F(1) - F(0)
\end{align}$

</center>

<p>Recalling that $e^p = \frac{a}{b}$, we conclude that </p>
<center>

$\begin{align}
b \int_{0}^{1} p^{2n+1}e^{px} f(x) \ dx = aF(1) - bF(0)
\end{align}$

</center>

<p>is an integer. As before, we can bound this integral from above:</p>
<center>

$\begin{align}
b \int_{0}^{1} p^{2n+1}e^{px} f(x) \ dx &lt; bp^{2n+1}e^p \frac{1}{n!} = \frac{ap^{2n+1}}{n!} &lt; 1
\end{align}$

</center>

<p>We get the last inequality by just taking a large enough $n$. There are no integers between 0 and 1, giving us our contradiction and completing the proof.</p>
<center>
$\blacksquare$
</center>


<!-- talk about wiener's attack after legendre's theorem -->
<p></br></p>
<h2 id="open-questions-and-more-strangeness">Open Questions and More Strangeness</h2>
<h3 id="irrational-powers">Irrational Powers</h3>
<p>But not much about irrationals are that well understood. It&#39;s quite simple to show that combining an rational with another rational number via addition, multiplication, division, and subtraction, only results in more rational numbers. Further, it&#39;s not too bad to show that combinations in the same way with an irrational and rational only lead to more irrationals. But combining irrationals are a little strange: obviously $(1 - \sqrt{2}) + \sqrt{2} = 1$ is the sum of two irrational numbers that result in a rational. You can even find two irrational numbers $a,b$ such that $a^b$ is rational.</p>
<hr>
<p><strong>Claim: There exists irrational numbers $a$ and $b$ such that $a^b$ is rational.</strong></p>
<p><strong>Proof:</strong> We know that $\sqrt{2}$ is irrational, so consider the number $\sqrt{2}^\sqrt{2}$. If this is rational, we&#39;re done. If this is irrational, then consider the number $(\sqrt{2}^\sqrt{2})^\sqrt{2} = \sqrt{2}^2 = 2$, which is rational, and hence we are done.</p>
<hr>
<p>In fact, it is possible to show for a lot of <a href="https://condor.depaul.edu/~mash/atotheamg.pdf">positive rational numbers $r$, there exists an irrational $a$ such that $a^a = r$</a>.</p>
<p><strong>Theorem:</strong> For every rational number $r \in \left( (1/e)^{1/e}, \infty \right)$, either $r = a^a$ for an irrational $a$, or $r \in \{1, 4, 27, 256, \cdots, n^n, \cdots \}$.</p>
<p><strong>Proof:</strong> Consider the function $f(x) = x^x$ on the interval $I = (1/e, \infty)$. $f(x)$ is continuous on $I$, since it is differentiable, and injective as it is monotonic (check derivative is strictly positive), so $f(I) = \left( (1/e)^{1/e}, \infty \right)$. So given a rational $r \in f(I)$, let $a \in I$ be the corresponding value such that $a^a = r$.</p>
<p>We&#39;ll now go and prove the contrapositive: if $a$ is rational and not an integer, then $a^a$ is irrational. In other words, if $r = \frac{p}{q}$, and $a = \frac{n}{m}$ are in lowest terms i.e. $\gcd(p,q) = \gcd(n,m) = 1$, and </p>
<center>

$\large \left( \frac{n}{m} \right)^\frac{n}{m}$ $= \large \frac{p}{q}$

</center>

<p>then $m = 1$ and $a$ must be an integer. So, for a contradiction, assume that $m &gt; 1$. Rearranging our equation, we get that </p>
<center>

$n^n q^m = p^m m^n$

</center>

<p>Since $\gcd(p,q) = 1$, a prime divides the factor $q^m$ on the left-hand side if and only if it divides the factor $m^n$ on the right-hand side. So $q^m = m^n$. Since $m &gt; 1$, we can write $q = \alpha^i k$ and $m = \alpha^j l$ for some prime $\alpha$ and integers $k,l$. Since $q^m = m^n$, we must also have $im = jn$ for the exponent of $\alpha$ to match. Thus $i(\alpha^j l) = jn$, and $\alpha^j$ divides $jn$.</p>
<p>But $\gcd(m,n) = 1$, and $\alpha^j$ is a factor of $m$, hence $\alpha^j$ divides $j$. So, $\alpha^j \leq j$. Since $\alpha$ is a prime, $2 \leq \alpha$, and so $2^j \leq j$. But it can easily be shown that $2^j &gt; j$ for all integers $j$, giving us the contradiction.</p>
<center>
$\blacksquare$
</center>

<h3 id="transcendental-numbers">Transcendental Numbers</h3>
<p>$\pi$ being irrational is a well-known fact among everyone. A more surprising fact to more mathematically inclined is the fact that $\pi$ is <em>transcendental</em>.</p>
<p>Not all irrational numbers are equal. $\sqrt{2}$ is, in some ways, <em>defined</em> by the fact that it is the (positive) root to $x^2 - 2 = 0$. Despite being, well, just a number that seems to exist as its own object, $\sqrt{2}$ has a decidedly algebraic quality to it which allows us to precisely specify it in much simpler terms (i.e. integers and arithmetic). Lots of numbers can be characterized as solutions to polynomials. Even imaginary numbers, which many find difficult to grasp, can be simply defined in terms of simple polynomials: $\pm i$ are the solutions to $x^2 + 1 = 0$.</p>
<p>But not <em>every</em> number can be defined via a polynomial. In fact, it&#39;s not too hard to show that there are only <a href="https://proofwiki.org/wiki/Algebraic_Numbers_are_Countable">countably many of these <strong>algebraic numbers</strong></a>, so certainly the unconutable $\mathbb{R}$ contains some non-algebraic or <strong>transcendental</strong> numbers. Two of which we are already familiar with: $\pi$ and $e$.</p>
<p>Proving numbers, especially $\pi$ and $e$, are not straightforward by any means, and simple statements of them were huge discussion points throughout math&#39;s history (see <a href="https://en.wikipedia.org/wiki/Hilbert%27s_seventh_problem">Hilbert&#39;s 7th Problem</a>), resulting in major theorems like the <a href="https://en.wikipedia.org/wiki/Lindemann%E2%80%93Weierstrass_theorem">Lindemann–Weierstrass theorem</a>. The first number to be discovered to be transcendental was one by Liouville, aptly called <em>Liouville&#39;s constant</em>:</p>
<center>

$\begin{align}
\sum_{n=1}^\infty \frac{1}{10^{n!}} = 0.11000100000000000000000100\ldots
\end{align}$

</center>

<p>and you can find a proof of its transcendence <a href="https://www.youtube.com/watch?v=c9nUAXUSuII">here</a>.</p>
<p>Maybe we&#39;ll come back to all this later, but for now, we&#39;ve done enough and can save it for another day.</p>
<!-- Erdos's irrational numbers: https://www.youtube.com/watch?v=6o5bHcluj8w&pp=ygUaZXJkb3MncyBpcnJhdGlvbmFsIG51bWJlcnM%3D -->
<!-- for transcendental numbers: Lindemann–Weierstrass theorem, Gelfond–Schneider theorem -->
]]></description>
         <link>http://xperimex.github.io/blog/pi-irrational</link>
         <guid isPermaLink="true">http://xperimex.github.io/blog/pi-irrational</guid>
         <dc:creator><![CDATA[Adi Mittal]]></dc:creator>
      </item>
      <item>
         <title><![CDATA[The Prime Number Theorem and Similar Mysteries]]></title>
         <description><![CDATA[Where modern number theory begins. 

 <p>It&#39;s not unfair to call prime numbers the foundation for not just number theory and mathematics, but many mathematicians&#39; careers. At an early age, around 7 years old in 1st-2nd grade in the US, kids learn multiplication and division. From there, we learn that we can break down numbers into smaller numbers, we call factors or divisors. For example,</p>
<center>
$2024 = 2 \cdot 2 \cdot 2 \cdot 11 \cdot 23$
</center>

<p>There is no &quot;simpler&quot; way to break down the number 2024. But then there&#39;s a very natural next question to ask upon learning about prime numbers for the first time: how do we know which numbers are prime? Unfortunately, there is not that a good of an answer to give to anyone, from the elementary school to college students. The only strategy you really have until college is just to try and divide the number in question, and see if there are any factors. You can make small optimizations by checking numbers less than $\sqrt{n}$, and skipping even numbers obviously, but at the end of the day, primes seem kind of random with little to no patterns available. This is one of the first real mysteries young mathematicians encounter.</p>
<p>Though, math has come a long way, and now slowly but surely we are starting to unravel the primes, revealing much about the simple numbers we count with to much more.</p>
<h1 id="table-of-contents">Table of Contents</h1>
<ul>
<li><a href="#what-is-a-prime-number-">What is a Prime Number?</a></li>
<li><a href="#some-foundational-results">Some Foundational Results</a></li>
<li><a href="#dont-take-these-for-granted">Don&#39;t Take These For Granted</a><ul>
<li><a href="#rings-and-algebraic-abstractions">Rings and Algebraic Abstractions</a></li>
<li><a href="#integral-domains-and-zero-divisors">Integral Domains and Zero Divisors</a></li>
<li><a href="#classifying-elements">Classifying Elements</a></li>
</ul>
</li>
<li><a href="#some-simple-patterns-and-useful-facts">Some Simple Patterns and Useful Facts</a></li>
<li><a href="#finding-primes">Finding Primes</a></li>
<li><a href="#primality-tests">Primality Tests</a><ul>
<li><a href="#trial-division">Trial Division</a></li>
<li><a href="#wilson-s-theorem">Wilson&#39;s Theorem</a></li>
<li><a href="#fermat-s-test">Fermat&#39;s Test</a></li>
<li><a href="#other-tests">Other Tests</a></li>
<li><a href="#different-types-of-primes">Different Types of Primes</a></li>
<li><a href="#prime-generating-formula">Prime Generating Formula</a></li>
</ul>
</li>
<li><a href="#sieves-and-filters">Sieves and Filters</a><ul>
<li><a href="#probability-of-being-prime">Probability of Being Prime</a></li>
</ul>
</li>
<li><a href="#distributions-and-the-prime-gap">Distributions and the Prime Gap</a><ul>
<li><a href="#bertrand-s-postulate">Bertrand&#39;s Postulate</a></li>
</ul>
</li>
<li><a href="#prime-number-theorem">Prime Number Theorem</a><ul>
<li><a href="#proof-of-the-prime-number-theorem">Proof of the Prime Number Theorem</a></li>
<li><a href="#do-we-need-the-primes-at-all-">Do We Need the Primes at All?</a></li>
</ul>
</li>
<li><a href="#consequences-of-the-prime-number-theorem">Consequences of the Prime Number Theorem</a><ul>
<li><a href="#analyzing-the-nth-prime">Analyzing the nth Prime</a></li>
<li><a href="#revisiting-bertrands-postulate">Revisiting Bertrand&#39;s Postulate</a></li>
<li><a href="#a-quick-application-of-the-pnt">A Quick Application of the PNT</a></li>
</ul>
</li>
<li><a href="#an-analogue-to-the-prime-number-theorem-in-k-x-">An Analogue to the Prime Number Theorem in $K[x]$</a></li>
<li><a href="#conclusion">Conclusion</a></li>
</ul>
<h2 id="what-is-a-prime-number-">What is a Prime Number?</h2>
<p>This isn&#39;t a trick question. Primes are still exactly what you (probably) think they are:</p>
<hr>
<p><strong>Definition 1:</strong> A positive integer is said to be <strong>prime</strong> if it is not the product of two smaller natural numbers (excluding 1), i.e. $p \neq ab$ with both $a, b \neq 1$. </p>
<hr>
<p>We cannot factor primes. This is partly why finding primes is so tricky—we define them not by what they are, but what they are not. This also gives a nice reason for why we should not consider $1$ prime: it just cannot be factored into smaller numbers. </p>
<p>It turns out, there is another, equivalent notion of being a prime number though.</p>
<!-- Good reason why 1 isn't prime: 1 = 1*1 and 1 is not less than 1. -->
<hr>
<p><strong>Definition 2:</strong> A positive integer (excluding 1) $p$ is <strong>prime</strong> if when $p \mid ab$, then $p \mid a$ or $p \mid b$.</p>
<hr>
<p>Here we are using $x \mid y$ to mean $x$ divides $y$. This notion of primality is kind of similar to the definition we are already familiar with: it basically characterizes the idea of prime $p$ being unable to be &quot;split up&quot; into smaller parts that can be distributed between $a$ and $b$. The factor must have contributed wholly to either $a$ or $b$, and did not magically appear by multiplying the two.</p>
<p><strong>Theorem:</strong> Definition 1 and Definition 2 are equivalent.</p>
<p><strong>Proof:</strong> Although these definitions do look and feel similar, actually arguing the equivalence rigorously is kind of difficult (as it turns out for much of math). </p>
<!-- idea: if p | a, then can factor out p and show that b * other factors = 1 -->
<p><strong>(Definition 2 $\Rightarrow$ Definition 1):</strong> Let&#39;s say $p \in \mathbb{N}$ satisfies Definition 2. Now suppose for contradiction that $p = ab$ with $a, b \neq 1$. Then, since all numbers divide themselves, $p \mid p = ab$. By the property in Definition 2, $p \mid a$ or $p \mid b$. Let&#39;s say $p \mid a$, so $a = pn$ for some $n$. Combining our equalities, we get $p = ab = pnb$. Rearranging, $p(1-nb) = 0$. Since $p \neq 0$, we get $1 = nb$. The only way this can happen is if $n = b = 1$ since they have to be positive integers, giving us our contradiction. Therefore, it must be the case that $p$ also satisfies Definition 1. A similar argument can be used for when $p \mid b$.</p>
<p><strong>(Definition 1 $\Rightarrow$ Definition 2):</strong> This is also known as <a href="https://en.wikipedia.org/wiki/Euclid%27s_lemma">Euclid&#39;s Lemma</a>. Say $p$ is prime according to Definition 1. Now suppose that $p \mid ab$, but $p \nmid a$. We&#39;ll show that $p \mid b$. The simplest proof I&#39;ve seen (without presupposing some results we&#39;ll later discuss) uses <a href="https://en.wikipedia.org/wiki/B%C3%A9zout%27s_identity">Bézout&#39;s Lemma</a>. Since $p \nmid a$ and $p$ has no factors itself, $\gcd(a,p) = 1$. By Bézout&#39;s, there are integers, $n$ and $m$ such that</p>
<center>
$np + ma = 1$
</center>

<p>Multiplying both sides by $b$, we get</p>
<center>
$npb + mab = b$
</center>

<p>Clearly, $p \mid npb$. By our assumption, $p \mid ab$ so $p \mid mab$. Therefore, $p \mid npb + mab = b$, giving us our conclusion.</p>
<center>
$\blacksquare$
</center>





<h2 id="some-foundational-results">Some Foundational Results</h2>
<p>Even with just these definitions and basic results, we can already start to make some headway. The following of which, is probably the most important theorem regarding the integers.</p>
<!-- need to prove: every number has a factorization -> unique factorization -> infinitely many primes -->
<p><strong>The Fundamental Theorem of Arithmetic:</strong> Every integer has a unique* prime factorization.</p>
<p><strong>Proof:</strong> We&#39;ll prove this in two steps.</p>
<p><strong>(Existence)</strong> Showing every integer has a prime factorization is exactly as you&#39;d expect intuitively: we&#39;ll break up a number into its factors as many times as possible until we hit its prime factorization. We&#39;ll do this by induction. </p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <strong>Base Case:</strong> $2 = 1\cdot 2$ has a trivial prime factorization being prime itself.</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <strong>Inductive Step:</strong> Say every number greater than 1 and less than $n$ has a prime factorization. If $n$ is prime, we&#39;re done. If $n$ is not prime, then it is possible to write $n=ab$ with $1&lt;a\leq b&lt;n$. By the inductive hypothesis, </p>
<center>
$a = p_1 p_2 \cdots p_k$ 
<br/>
$b = q_1 q_2 \cdots q_\ell$ 
</center>

<p>have prime factorizations. Combining these, we see that</p>
<center>
$n = p_1 p_2 \cdots p_k q_1 q_2 \cdots q_\ell$ 
</center>

<p>is also a product of primes.</p>
<p><strong>(Uniqueness)</strong> Say there are integers that don&#39;t have a unique prime factorization. Let </p>
<center>
$n = p_1 p_2 \cdots p_k = q_1 q_2 \cdots q_\ell$
</center>

<p>be the <em>least</em> integer with two such factorizations. Therefore, $p_1 \mid q_1 q_2 \cdots q_\ell$. By Definition 2 and Euclid&#39;s Lemma, that means $p_1 \mid q_i$ for some $i=1,\cdots,\ell$. Let&#39;s suppose (without loss for generality) that $p_1 \mid q_1$. Since $q_1$ is prime, we must have $p_1 = q_1$. That means we can divide both of these out and get that</p>
<center>
$m = p_2 \cdots p_k = q_2 \cdots q_\ell$
</center>

<p>But then we have found some integer $m &lt; n$ that has two distinct prime factorizations, contradicting the minimality of $n$.</p>
<p><br/></p>
<p>Proving factorization for the negative integers is essentially the same, just noting the extra inclusion of $-1$ as a factor.</p>
<hr>
<p>*the uniqueness of factorization seems like a proper fact now that we&#39;ve proved it, but there are a few hiccups we need to address. For one, this factorization is unique up to reordering of the primes; $10 = 2 \cdot 5 = 5 \cdot 2$. This is not that problematic, and can be pretty well understood since we&#39;re working with integers and know multiplication is commutative. However, only that we haven&#39;t fully explained one small bit away: we can include extra factors of $1$. This seems kind of redundant since we have already said $1$ isn&#39;t prime, and it&#39;s just kind of obvious to ignore the fact that $2 = 1\cdot 2 = 1\cdot 1 \cdot 2 = \cdots$. But this is an issue if we&#39;re going to allow $-1$ in the factorizations of negative numbers. After all, $6 = 2 \cdot 3 = (-2) \cdot (-3)$. So what we can do is combine and push to the front all these extra factors of $1$ and $-1$, and make that sign-determining factor included as a non-prime unique divisor. <strong>Let this reinforce that 1 is not a prime number</strong>.</p>
<center>
$\blacksquare$
</center>

<p><a href="https://xperimex.com/blog/pi-irrational/#completeness-and-the-variety-of-irrationals">Last post</a>, we discussed how the irrational numbers were the key to the real numbers; the irrationals are what give the distinguishing properties of the reals. Even if the names are suggestive, it really should be noted how important the irrationals are to separating the reals and the rationals. </p>
<p>The prime numbers serve a similar purpose to the integers. In fact, because of the above theorem and unique factorization, primes are basically <em>all</em> you need to discuss results about the integers (and that is reflected in many theorems, which we&#39;ll mention later).</p>
<p>From this we immediately get another major, fundamental result about the primes.</p>
<p><strong>Theorem:</strong> There are infinitely many prime numbers.</p>
<p><strong>Proof (Euclid):</strong> Say there were only finitely many primes $p_1, p_2, \cdots, p_n$. Consider the following number:</p>
<center>
$\begin{align} p_1 p_2 \cdots p_n = \prod_{i=1}^n p_i \end{align}$
</center>

<p>So all of our primes divide this number. Now consider the number $P = p_1 p_2 \cdots p_n + 1$. We know $P$ has a unique prime factorization by the above. Since all of our primes come from the list $p_1, p_2, \cdots, p_n$, some $p_i \mid P$. But then</p>
<center>
$p_i \mid P - p_1 p_2 \cdots p_n = 1$
</center>

<p>So $p_i = 1$, which is impossible given $p_i$ is prime. So in reality, $P$ must have a prime divisor <em>not</em> in our original list, giving us the contradiction that there were only finitely many primes.</p>
<center>
$\blacksquare$
</center>

<p>Note exactly what this proof is saying: this doesn&#39;t say that $p_1 p_2 \cdots p_n + 1$ is prime, it only says that it contains a <em>new</em> prime divisor not found in the list $\{p_1, p_2, \cdots, p_n \}$.</p>
<p>This is a great result, but at the same time, this only widens the mystery and makes finding a pattern—if there is one—all the more unlikely. There is definitely something interesting to be said if there were only finitely many primes, but I think there being so many with such simple-to-state questions about them being unanswered kind of annoying.</p>
<h2 id="don-t-take-these-for-granted">Don&#39;t Take These For Granted</h2>
<p>Before delving further into common tools and patterns found in the primes, it is worth taking a second to note just how nice some of the properties they have—even though everyone likes to make they seem super mysterious.</p>
<h3 id="rings-and-algebraic-abstractions">Rings and Algebraic Abstractions</h3>
<p>The integers, in the broad perspective of higher math, is the simplest example of what is known as a <strong>ring</strong>.</p>
<p><strong>Definition:</strong> A <strong>ring</strong> $(R,+,\times,0,1)$ is a set $R$ given the following structure:</p>
<ul>
<li>$(R,+)$ is an <em>abelian group</em> with identity 0. In other words, $(R,+)$ has the properties <ul>
<li>Commutativity: $a+b = b+a$</li>
<li>Associativity: $a + (b + c) = (a + b) + c$</li>
<li>Identity: $ a + 0 = 0 + a = a$</li>
<li>Inverses: $\forall a \ \exists b \ (a + b = 0)$</li>
</ul>
</li>
<li>$\times: R\times R\rightarrow R$ has the following properties:<ul>
<li>Associativity: $a \times (b \times c) = (a \times b) \times c$</li>
<li>Identity: $a \times 1 = 1 \times a = a$</li>
<li>(Left) Distributivity: $a\times (b+c) = (a\times b) + (a\times c)$ </li>
<li>(Right) Distributivity: $(b+c) \times a = (b\times a) + (c\times a)$</li>
</ul>
</li>
</ul>
<p>This definition does look arbitrary and pretty complicated at first glance—and to be honest, it kind of is—but there&#39;s no denying its resemblance to the properties of addition and multiplication of the integers. In fact, you could just let $R = \mathbb{Z}$ and interpret $+$ and $\times$ as normal, and you would just get all of our normal arithmetic. As long as you keep those in mind, the definition should become more tractable. The hope is essentially to take some results and intuitions from the integers and extend them to other mathematical objects.</p>
<p>It turns out, with such a broad definition, a lot of algebraic work gets done that has seemingly nothing to do with the &quot;structure of the integers&quot;. Some major theorems include:</p>
<ul>
<li>The Chinese Remainder Theorem: existence of unique solution to system of modulo remainders</li>
<li>Eisenstein&#39;s Criterion: a sufficient condition on when integer polynomials can be factored</li>
<li>The classification of finitely generated abelian groups</li>
<li>Proving the existence of Jordan and Rational Canonical Forms for linear maps</li>
</ul>
<p>Rings are kind of magical in that way in that they are by far one of the least-obvious tools to employ, but when used correctly, the generality of the theory can lead to a lot. They are unsurprisingly the basis for lots of higher level algebra, especially number theory.</p>
<h3 id="integral-domains-and-zero-divisors">Integral Domains and Zero-Divisors</h3>
<p>But not all rings act as nicely as $\mathbb{Z}$. For example, we tend to overlook how convenient it is that $\mathbb{Z}$ is an <strong>integral domain</strong>. That is,</p>
<center>
$ab = 0 \Rightarrow a = 0 \ \textrm{or} \ b = 0$
</center>

<p>This is a trick we use when solving for roots of polynomials (which is another ring). If you wanted to solve the quadratic,</p>
<center>

$\begin{align}
x^2 - 5x + 6 = 0 &amp; \Rightarrow \\
(x-2)(x-3) = 0 &amp; \Rightarrow \\ \hline
\end{align}$
</br>
$x-2 = 0 \ \textrm{or} \ x-3=0$
</center>

<p>That last step is only justified in integral domains. If you&#39;re working in the ring, say, the integers modulo 10 </p>
<center>
$\mathbb{Z}_{10} = \{\bar{0},\bar{1},\bar{2},\cdots,\bar{9}\}$
</center>

<p>then we can very much have <strong>zero divisors that break the integral domain property</strong>. </p>
<center>
$\bar{2} \times \bar{5} = \bar{10} = \bar{0}$
</center>

<p>If you look back at some of our proofs, like in showing the equivalence of Definitions 1 and 2 of prime numbers, having zero divisors would not allow us to conclude our results.</p>
<h3 id="classifying-elements">Classifying Elements</h3>
<p>In the same way we classify integers as prime or not, we can do a similar organization of ring elements:</p>
<ul>
<li><strong>Unit:</strong> $x \in R$ is a unit if it has a multiplicative inverse i.e. $\exists y \ \textrm{s.t.} \ xy=1$</li>
<li><strong>Irreducible:</strong> A (non-unit) $x \in R$ is irreducible if it cannot be factored into non-units</li>
<li><strong>Prime:</strong>  A (non-unit) $x \in R$ is prime if when $x \mid ab$, then $x \mid a$ or $x \mid b$</li>
</ul>
<p>This is partly why I said there were 2 definitions of prime numbers at the top of this post: they are <em>truly separate definitions</em> of two different types of elements in a general ring. It just happens that the notion of being prime and irreducible are the same in the integers. Even though we think of these notions as intertwined by our intuitions of the prime, they can turn out separate.</p>
<p>If every element in the ring (except 0) is a unit, then we have a <strong>special type of ring called a field</strong>, which give us especially nice properties that we see most commonnly used for vector spaces. And although we haven&#39;t mentioned them yet by name, we&#39;ve run into units already in the form of $1$ and $-1$: they&#39;re the reason we need to clarify the Fundamental Theorem of Arithmetic, since <em>everything</em> is a multiple of a unit and made it unclear if we actually had unique prime factorization.</p>
<p>In some rings, though, we <strong>might genuinely lose unique factorization</strong>. Consider the ring</p>
<center>
$\mathbb{Z}\left[ \sqrt{-5} \right] = \{a+b\sqrt{-5} \ | \ a,b \in \mathbb{{Z}} \}$
</center>

<p>Then, in this ring, we get that</p>
<center>
$6 = 2 \cdot 3 = (1 + \sqrt{-5})(1-\sqrt{-5})$
</center>

<p>As such, the integers are known as a <strong>unique factorization domain (UFD)</strong> since it doesn&#39;t suffer from such a problem.</p>
<hr>
<p>Those are some examples and a peak into abstract algebra. Hopefully it gives some appreciation for why the integers and primes numbers are special in their own way, but we&#39;ve covered enough ring theory for today and perhaps will revisit it later down the road.</p>
<!-- maybe talk about field -> ED -> PID -> UFD ? -->
<h2 id="some-simple-patterns-and-uses-of-the-primes">Some Simple Patterns and Uses of the Primes</h2>
<p>To build up a bit more familiarity with the primes, its worth perusing some of the simple patterns and ways the primes can be leveraged. Here&#39;s a simple one that isn&#39;t too hard to notice.</p>
<p><strong>Claim:</strong> Every prime is of the form $6n \pm 1$.</p>
<p><strong>Proof:</strong> Just check the other cases:</p>
<ul>
<li>$6n \pm 2 = 2(6n \pm 1)$ so these can&#39;t be prime</li>
<li>$6n \pm 3 = 3(6n \pm 1)$ so these can&#39;t be prime</li>
</ul>
<p>Another simple pattern.</p>
<p><strong>Claim:</strong> For $p &gt; 2$ prime, $24 \mid p^2 - 1$.</p>
<p><strong>Proof:</strong> $p^2 - 1 = (p-1)(p+1)$. Now $p$ is odd, so $(p-1)$ and $(p+1)$ are even. Moreover, these are consecutive even numbers, so while one is only divisble by 2 the other is actually divisble by 4. Finally, $p$ being prime means it isn&#39;t a multiple of 3, but $(p-1),p,(p+1)$ are 3 consecutive numbers. So again, one of $(p-1)$ and $(p+1)$ is divisible by 3. All together, we have collected that $p^2 - 1 = (p-1)(p+1)$ has at least the factors of $2 \cdot 4 \cdot 3 = 24$. $\blacksquare$</p>
<p>Here&#39;s a much more famous one.</p>
<p><strong>Fermat&#39;s Little Theorem:</strong> For any integer $a$ and $p$ prime, $a^{p} \equiv a \bmod p$.</p>
<p><strong>Proof:</strong> Note if $a \equiv 0 \bmod p$, then the result follows. So we just need to show $a^{p-1} \equiv 1 \bmod p$ for $a \neq kp$. Consider the set of numbers $\{a,2a,3a,\cdots,(p-1)a\}$. Note that these are all distinct residues modulo $p$; consider when two residues of this type are equal $ia \equiv ja \bmod p$. So $(i-j)a \equiv 0 \bmod p$. Since $p$ is prime and doesn&#39;t divide $a$, by Euclid&#39;s Lemma, $p \mid i-j$ i.e. $i \equiv j \bmod p$. So, the set $\{a,2a,3a,\cdots,(p-1)a\}$ is really just a reshuffling of the $p-1$ residues $\{1,2,3,\cdots,p-1\}$ (since there are $p-1$ numbers in the set, and they are all distinct modulo $p$). Therefore,</p>
<center>
$\begin{align} 
a \cdot 2a \cdot 3a \cdots (p-1)a \equiv 1 \cdot 2 \cdot 3 \cdots (p-1) \bmod p 
\end{align}$
</center>

<p>Since $p \nmid (p-1)!$, we can divide this out with Euclid&#39;s Lemma, and we arrive at $a^{p-1} \equiv 1 \bmod p$.</p>
<center>
$\blacksquare$
</center>

<hr>
<p>Just as we talked about how ring theory fits into number theory briefly, it might not be surprising to see that its cousin group theory plays a big role as well. The proof of Fermat&#39;s Little Theorem simplifies quite a bit with the tools of groups, and much of what we bothered proving above is group theory in disguise.</p>
<p><strong>Proof with Groups:</strong> Note that $\{1,2,\cdots,p-1\} = (\mathbb{Z}/p\mathbb{Z})^{\times}$ is a group under multiplication. Consider some $a \in (\mathbb{Z}/p\mathbb{Z})^{\times}$, and its cyclic subgroup $A = \{1,a,a^2,\cdots,a^{k-1}\}$. $|A| = k$, and by Lagrange&#39;s Theorem, $|A|$ divides $|(\mathbb{Z}/p\mathbb{Z})^{\times}| = p-1$. So $p-1 = k \ell$ for some $\ell$, and $a^{p-1} = a^{k \ell} = (a^k)^\ell = 1^\ell = 1$. $\blacksquare$</p>
<hr>
<p>Given how much interest there is in them, it shouldn&#39;t be surprising that there are so many number theory results about the primes.</p>
<p><strong>Wilson&#39;s Theorem:</strong> For $p$ prime, $(p-1)! \equiv -1 \bmod p$.</p>
<p><strong>Proof:</strong> Note for all numbers $x \in \{1,2,3,\cdots,p-1\}$, they each have a multiplicative inverse i.e. $\exists y \ \textrm{s.t.} \ xy = 1$. This is best seen by using Bézout&#39;s Lemma: since $\gcd(x,p)=1$ as $p$ is prime, there exists $n,m$ such that $nx+mp=1$. Thus this reduces to $nx \equiv 1 \bmod p$, showing the existence of a multiplicative inverse $n$. </p>
<p>Further, note that $1$ and $p-1$ are the only numbers to be their own inverse. To see this, we essentially want to solve $a \equiv a^{-1} \bmod p$ or equivalently $a^2 \equiv 1 \bmod p$. Further, we&#39;re solving $a^2 - 1 = (a-1)(a+1) \equiv 0 \bmod p$. So $p \mid (a-1)(a+1)$, and since $p$ is prime, $p \mid (a-1)$ or $p \mid (a+1)$. In the language of residues, this means that $a \equiv \pm 1 \bmod p$ which reduces to either $1$ or $p-1$.</p>
<p>Now back to the theorem at hand, if we consider $(p-1)! = 1 \cdot 2 \cdot 3 \cdots (p-1)$, all the numbers except $1$ and $p-1$ pair off with their inverses, cancelling each other out. Thus $(p-1)! \equiv 1 \cdot (p-1) \equiv -1 \bmod p$.</p>
<center>
$\blacksquare$
</center>

<p>Here&#39;s another result that illustrates in particular how useful unique factorization of the primes is.</p>
<p><strong>Theorem:</strong> A finite product of countable sets is countable.</p>
<p><strong>Proof:</strong> We&#39;ll show this for the case of infinitely countable sets, since 1) the product of finite sets is obvious, and 2) the definition of countability relies on injections from a set to $\mathbb{N}$, so countability of products of sets will follow if we can show $\mathbb{N}^{k}$ is countable. If we have countable sets $A_1, A_2, \cdots, A_k$, we then have injections $f_i : A_i \rightarrow \mathbb{N}$. Then we have the injection $g: A_1 \times \cdots \times A_k \rightarrow \mathbb{N}^k$</p>
<center>
$g(a_1, a_2, \cdots, a_k) = (f_1(a_1), f_2(a_2), \cdots, f_k(a_k))$
</center>

<p>So the countability of $A_1 \times \cdots \times A_k$ will follow from the countability of $\mathbb{N}^k$. So consider the injection $F: \mathbb{N}^k \rightarrow \mathbb{N}$.</p>
<center>
$F(n_1, n_2, \cdots, n_k) = 2^{n_1} 3^{n_2} 5^{n_3} \cdots p_k^{n_k}$
</center>

<p>where $p_i$ is the $i^\textrm{th}$ prime number. By the Uniqueness of Factorization, $F$ is injective. For completeness, $F \circ g : A_1 \times \cdots \times A_k \rightarrow \mathbb{N}$ shows $A_1 \times \cdots \times A_k$ is countable.</p>
<center>
$\blacksquare$
</center>

<p>This ability to uniquely encode integers by their prime factorization is a nice trick to hold onto, especially for problems that involve <em>all</em> the natural numbers, giving us a path to break the problems up into the more &quot;fundamental&quot;, smaller parts.</p>
<p><strong>Euler&#39;s Product Formula:</strong> $\begin{align} \sum_{n=1}^\infty \frac{1}{n^s} = \prod_{p \ \textrm{prime}} \frac{1}{1-p^{-s}} \end{align}$</p>
<p><strong>Proof:</strong> The trick is essentially just the use of the Fundametal Theorem of Arithmetic in a generating function-style way. If you write the sum out with prime factors, the relation becomes clear:</p>
<center>
$\begin{align}
\sum_{n=1}^\infty \frac{1}{n^s} &amp; = 1 + \frac{1}{2^s} + \frac{1}{3^s} + \frac{1}{4^s} + \frac{1}{5^s} + \frac{1}{6^s} + \frac{1}{7^s} + \cdots \\
&amp; = 1 + \frac{1}{2^s} + \frac{1}{3^s} + \frac{1}{2^s \cdot 2^s} + \frac{1}{5^s} + \frac{1}{2^s \cdot 3^s} + \frac{1}{7^s} + \cdots \\ 
&amp; = \left(1 + \frac{1}{2^s} + \frac{1}{2^{2s}} + \frac{1}{2^{3s}} + \cdots \right)\left(1 + \frac{1}{3^s} + \frac{1}{3^{2s}} + \frac{1}{3^{3s}} + \cdots \right)\cdots \\
&amp; = \left(\frac{1}{1 - \frac{1}{2^s}} \right)\left(\frac{1}{1 - \frac{1}{3^s}} \right)\left(\frac{1}{1 - \frac{1}{5^s}} \right)\left(\frac{1}{1 - \frac{1}{7^s}} \right) \cdots \\
&amp; = \prod_{p \ \textrm{prime}} \frac{1}{1-p^{-s}} 
\end{align}$
</center>

<p>The 4th and 5th equalities follow from being products of geometric series. The key step is the 3rd equality. If you consider any term generated by that infinite product, you&#39;re essentially picking out which prime factors the denominator gets; when you consider each factor, you&#39;re asking, &quot;How many of this prime factor does my denominator get?&quot; By the Fundamental Theorem of Arithmetic, prime factorizations are unique and thus this process of choosing prime factors means each term $\frac{1}{n^s}$ appears once and only once. At least, that&#39;s the idea for why this formula <em>should</em> work. To actually prove the sum and product are the same, you have to give a bit more effort using the absolute convergence of that sum on the left. $\blacksquare$</p>
<hr>
<p>The sum we discussed above is famously known as the <strong>Riemann zeta function</strong> $\zeta(s)$, the center of the even more famously open million-dollar <strong>Riemann Hypothesis</strong> problem. Even without name, you probably have seen individual instances of the zeta function before, as individual instances of the function have been studied for hundreds of years.</p>
<ul>
<li>$\zeta(1) = \sum_{n=1}^\infty \frac{1}{n}$ is the divergernt <strong>harmonic series</strong></li>
<li>$\zeta(2) = \sum_{n=1}^\infty \frac{1}{n^2} = \frac{\pi^2}{6}$ is the <strong>Basel problem</strong></li>
<li>$\zeta(3) = \sum_{n=1}^\infty \frac{1}{n^3} \approx 1.2020578$ is <strong>Apéry&#39;s constant</strong>, named after the man who proved it irrational</li>
</ul>
<p>The most useful of which to keep in mind for most people is probably the harmonic series $\zeta(1)$, as it appears as an incredibly useful example in bounding series and proving contradictions, being one of the simplest divergent series there is. Here&#39;s a neat example proving a fact we already know.</p>
<p><strong>Theorem:</strong> There are infinitely many primes.</p>
<p><strong>Proof (Euler):</strong> Say there were only finitely many primes $p_1,p_2,\cdots,p_n$. Then consider the product</p>
<center>
$\begin{align} \prod_{i=1}^n \left( 1 + \frac{1}{p_i} + \frac{1}{p_i^2} + \frac{1}{p_i^3} + \cdots \right) = \prod_{i=1}^n \left( \frac{1}{1 - \frac{1}{p_i}} \right) \end{align}$
</center>

<p>The righthand side is obtained since each $p_i &gt; 1$ i.e. $\frac{1}{p_i} &lt; 1$, thus making each geometric series converge. So this finite product of geometric series converges to some value.</p>
<p>Note, however, that since every integer has a unique prime factorization, we can see that this product is equivalent to </p>
<center>
$\begin{align} 1 + \frac{1}{2} + \frac{1}{3} + \frac{1}{4} + \frac{1}{5} + \cdots = \sum_{k=0}^\infty \frac{1}{k} \end{align}$
</center>


<p>(think Euler&#39;s Product Formula). But we know that the harmonic series diverges, giving us our contradiction. So there must be infinitely many primes.</p>
<center>
$\blacksquare$
</center>

<p>The nice thing about this proof for me is that it begins to illustrate some of the more calculus-y tools we have at our disposal to prove facts about the integers. The field of <em>analytic number theory</em> and using results commonly associated with continuous functions or the real numbers to show facts of the integers always feels a bit surprsing to me, but this proof is a nice introduction to the topic.</p>
<h2 id="finding-primes">Finding Primes</h2>
<p>The above results are interesting and actually quite useful, but to be used in practice requires actually <em>knowing a number is prime</em>. If you don&#39;t mind just having existence of a solution or proof, like we did in the countability proofs, then you have most of what you want already. But having an actual list of prime numbers, or at least knowing <em>where</em> to find prime numbers is often needed to apply some of our powerful results on primes. If we didn&#39;t look for them, cryptography, for one, would completely break down along side all of online security.</p>
<h2 id="primality-tests">Primality Tests</h2>
<h3 id="trial-division">Trial Division</h3>
<p>One way we can find primes is by having some criterion $\Phi(n)$ that can tell us if $n$ is prime or not. The simplest test is to just check a number satisfies one of our definitions of being prime. This is probably the original test we all tried at some point: sitting down and just manually checking if a number has any divisors besides itself. Of course, we can do some simple optimizations to avoid needless division.</p>
<ul>
<li>If the number is even, it&#39;s not prime</li>
<li>If the number ends in 0 or 5, then it&#39;s divisible by 5 and not prime</li>
<li>We only need to check numbers of the form $6k \pm 1$</li>
<li>We only need to check the prime divisors up to $\sqrt{n}$</li>
</ul>
<p>and a whole host of other simple division rules that we can use to simplify this process. Though, as I&#39;m sure we&#39;ve all felt doing this process, it&#39;s not great and there must be a better way. In fact, we should be glad that trial division and factoring directly is hard, as again, much of modern cryptography relies on the assumption that determining prime factorization is difficult.</p>
<h3 id="wilson-s-theorem">Wilson&#39;s Theorem</h3>
<p>You may not have realized it yet, but we&#39;ve already seen a more sophisticated primality test with <strong>Wilson&#39;s Theorem</strong>. If $n$ is <em>not</em> prime, then there are two cases:</p>
<ol>
<li>$n$ can be written as $n=ab$ with $a \neq b$. Since $a,b&lt;n$, it must be that $a,b$ appear somewhere in the list $\{1,2,\cdots,(n-1)\}$, meaning that $(n-1)! = 1 \cdot 2 \cdots (n-1)$ is a multiple of $n$ i.e. $(n-1)! \equiv 0 \bmod n$.</li>
<li>If $n$ cannot be written like in Case 1, then $n = p^2$ for some prime $p$ (if $n$ had 2+ distinct prime factors, we can find $a,b$ to be in Case 1). But $2p &lt; p^2 = n$ for $p&gt;2$. So the numbers $p, 2p$ appear somewhere in $1 \cdot 2 \cdots (n-1)$ i.e. $n = p^2 \mid (n-1)!$ and thus $(n-1)! \equiv 0 \bmod n$.</li>
</ol>
<p>So if $n$ is composite, $(n-1)! \equiv 0 \bmod n$. The only exception is for $n = 4$ where $(4-1)! = 6 \equiv 2 \bmod 4$, but that&#39;s fine since $2 \not\equiv -1 \bmod 4$.</p>
<p><strong>Wilson&#39;s Theorem:</strong> $n$ is prime if and only if $(n-1)! \equiv -1 \bmod n$.</p>
<p>But this test is not great, as you can imagine it grows exponentially worse to evaluate $(n-1)!$ as $n$ grows larger, even despite <a href="https://www.quantamagazine.org/mathematicians-discover-the-perfect-way-to-multiply-20190411/">advances in multiplication</a>.</p>
<h3 id="fermat-s-test">Fermat&#39;s Test</h3>
<p>Inspired by Wilson&#39;s Theorem, we might be inclined to see if our other theorems about prime numbers are sufficient tests. How about Fermat&#39;s Little Theorem? While we have only shown it&#39;s a necessary condition to being prime, there is a formulation for it being sufficient as well.</p>
<p><strong>Fermat&#39;s Little Theorem:</strong> $p$ is prime if and only if $a^{p-1} \equiv 1 \bmod p$ for all $a \in \{1,2,\cdots,n-1\}$.</p>
<p><strong>Proof of Converse:</strong> We&#39;ll show the contrapositive. Say $n$ is composite i.e. $n$ has a divisor $\exists d \ \textrm{s.t.} \ d \mid n$. Suppose that $d^{n-1} \equiv 1 \bmod n$ i.e. $d^{n-1} = 1 + kn$ for some $k$, or more helpfully, $d^{n-1} - kn = 1$. $d$ divides $n$, so $d \mid d^{n-1} - kn = 1$, so $d = 1$, giving us our contradiction. Hence if $n$ is composite, we have found a number such that $d^{n-1} \not\equiv 1 \bmod n$. $\blacksquare$</p>
<p>There are a couple reasons why using FLT as a criterion so much better than what Wilson&#39;s theorem provides.</p>
<p><strong>1) Exponentiation:</strong> Computing multiplication—especially factorials—is slow, but exponentiation is relatively easy due it being <em>repeated</em> multiplication of the same number. For example, here&#39;s a common trick using repeated squaring to compute exponents $a^n \bmod p$.</p>
<ol>
<li>Write $n$ in binary i.e. $n = c_0 2^0 + c_1 2^1 + \cdots + c_k 2^k$ where $c_i \in \{0,1 \}$</li>
<li>Iteratively compute $a^{2^i} = (a^{2^{i-1}})^2 \bmod p$ i.e. Find $a^{2}$, then $a^{2^2} = (a^2)^2$, then $a^{2^3} = (a^{2^3})^2$ reduced $\textrm{mod} \ p$</li>
<li>Calculate $a^n = a^{c_0 2^0 + c_1 2^1 + \cdots + c_k 2^k} = (a^{2^0})^{c_0} \cdot (a^{2^1})^{c_1}  \cdots (a^{2^k})^{c_k} \bmod p$</li>
</ol>
<p>Expanding $n$ into binary caps the size of the total number of multiplications and divisions we compute to be proportional to $\log(n)$ as opposed to $n$, making this fairly efficient to compute $\textrm{mod} \ p$.</p>
<p><strong>2) Multiple Computations:</strong> While if we want a <em>definitive</em> proof that a number is prime, we will have to compute $a^{p-1} \bmod p$ for every value of $a$, we can stop our test whenever we want. We can only check some values, even just a single one if we wanted, and expedite the calculations. These sped up tests aren&#39;t definitive, but they can give us <strong>probable prime numbers</strong>.</p>
<p>The second benefit is what leads us to make this prime-testing algorithm:</p>
<p><strong>Fermat Primality Test:</strong> To check if $p$ is prime, repeat the following $k$ times:</p>
<ol>
<li>Pick a number uniformly $a \in \{2,\cdots,p-1\}$</li>
<li>Compute $a^{p-1} \bmod p$<ul>
<li>If $a^{p-1} \not\equiv 1 \bmod p$, return &quot;$p$ is composite&quot;</li>
</ul>
</li>
</ol>
<p>Here, we let $k$ be a type of threshold if we accept $p$ to be prime if we&#39;re okay not being 100% certain with our test result to cut down computational cost. It must be reiterated, this really is a <strong>probable test</strong> if we don&#39;t check every number. For example,</p>
<center>
$2^{340} \equiv 1 \bmod 341$
</center>

<p>but $341 = 11 \cdot 31$. We can have false positives if we rely on this criterion. But if we do another test,</p>
<center>
$3^{340} \equiv 56 \bmod 341$
</center>

<p>we can find a <strong>Fermat witness</strong> to show 341 is composite. False positives might seem to preclude us from using this test, but there&#39;s a nice property that gives us reason to use this as an efficient test.</p>
<hr>
<p><strong>Claim:</strong> If a composite number $n$ has a Fermat witness $a$ with $\gcd(a,n)=1$, then at least half of the numbers $\{1,2,3,\cdots, n-1\}$ are Fermat witnesses.</p>
<p><strong>Proof:</strong> Let&#39;s call $S = \{1,2,3,\cdots, n-1\}$, and we&#39;ll consider the following 3 sets:</p>
<center>
$\begin{align}
A &amp; = \{a \in S \ : \ a^{n-1} \equiv 1 \bmod n \textrm{ &amp; } \gcd(a,n) = 1 \} &amp; | \ \textrm{Numbers that pass the test} \\
B &amp; = \{b \in S \ : \ b^{n-1} \not\equiv 1 \bmod n \textrm{ &amp; } \gcd(b,n) = 1 \} &amp; | \ \textrm{Non-trivial Fermat witnesses} \\
% C &amp; = \{c \in S \ : \ c^{n-1} \equiv 1 \bmod n \textrm{ &amp; } \gcd(c,n) &gt; 1 \} &amp; | \ \textrm{Empty set} \ \varnothing \\
C &amp; = \{c \in S \ : \ \gcd(c,n) &gt; 1 \} &amp; | \ \textrm{Trivial Fermat witnesses} \\
\end{align}$
</center>

<p>Clearly all these sets are disjoint.</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <strong>Claim:</strong> $C$ is the trivial Fermat witnesses.</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <strong>Proof:</strong> Essentially the same proof why divisors are Fermat witnesses. Say $x \in S$ with $\gcd(x,n) = d &gt; 1$. Suppose that $x^{n-1} \equiv 1 \bmod n$, so $x^{n-1} = 1 + kn$. $d \mid x$ and $d \mid n$, so $d \mid x^{n-1} - kn = 1$, contradicting $d&gt;1$. So $x^{n-1} \not\equiv 1 \bmod n$. $\blacksquare$</p>
<!-- By showing all the non-coprime integers are Fermat witnesses, we have also shown that $C = \varnothing$.

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; **Corollary:** $C = \varnothing$ -->
<!-- &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; **Proof:** Essentially the same proof why divisors are Fermat witnesses. Say $c \in C$ with $\gcd(c,n) = d > 1$. $c^{n-1} \equiv 1 \bmod n$ means $c^{n-1} = 1 + kn$. $d \mid c$ and $d \mid n$, so $d \mid c^{n-1} - kn = 1$, contradicting $d>1$. So $C = \varnothing$. -->
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <strong>Claim:</strong> $A,B,C \neq \varnothing$</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <strong>Proof:</strong> $1 \in A$ so $A\neq \varnothing$. $B \neq \varnothing$ by assumption. $C \neq \varnothing$ since $n$ is composite and its divisors are in $D$.</p>
<p>What we are interested in showing is that $B$, the non-trivial Fermat witnesses, has a lot of elements. What we&#39;ll show is that $|B| + |C| \geq \frac{1}{2} S$, and we&#39;ll do this in a similar way we proved Fermat&#39;s Little Theorem by &quot;permuting&quot; elements with multiplication.</p>
<p>Pick any $b \in B$, and consider the set $Ab = \{ab \bmod n \ : \ a \in A\}$.</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <strong>Claim:</strong> $Ab \subseteq B$, and $|Ab| = |A|$</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <strong>Proof:</strong> Pick any $a \in A$, and consider $ab \in Ab$. Since $\gcd(a,n) = \gcd(b,n) = 1$, we get that $\gcd(ab,n) = 1$. Also, note that $(ab)^{n-1} \equiv a^{n-1} b^{n-1} \equiv b^{n-1} \not\equiv 1 \bmod n$. Hence $ab \in B$ for all $a \in A$, i.e. $Ab \subseteq B$. For the second half, note that since $\gcd(b,n) = 1$, we can imply that $(a_1 b \equiv a_2 b \bmod n \Rightarrow a_1 \equiv a_2 \bmod n)$. So the elements of $Ab$ are distinct, and hence $|Ab| = |A|$. $\blacksquare$</p>
<p>So we have that $|A| = |Ab| \leq |B|$. Therefore, since $A \cup B \cup C = \{1,2,\cdots,n-1\}$ and they are distinct, as well as $|A|,|B|,|C| &gt; 0$ by being non-empty, we have</p>
<center>
$|S| = n-1 = |A| + |B| + |C| \geq |A| + |A| + 1 &gt; 2|A|$
</center>

<p>Hence, $|A| &lt; \frac{1}{2} (n-1)$, and so its complement $|A^c| = |B| + |C| &gt; \frac{1}{2}(n-1)$. </p>
<center>
$\blacksquare$
</center>

<p><br/></p>
<p>It&#39;s worth mentioning, like with Fermat&#39;s Little Theorem, there is a group theoretic proof of this. If you&#39;re familiar with groups, the above looks a lot like we&#39;re working with cosets indirectly. The idea is that we look at the group $G = (\mathbb{Z}/n\mathbb{Z})^{\times}$ (since $n$ is composite, we look only at the invertible elements), and note that $A$ above as the set of numbers that pass the test form a subgroup. If there is a non-trivial Fermat witness i.e. $B \neq \varnothing$, then $A$ is a proper subgroup so $|G/A| \geq 2$, and hence $|A|$ can only contain at most half of the elements of $G$ (Lagrange&#39;s Theorem), and hence further that $|A|$ contains less than half of the full set $\{1,2,\cdots,n-1\}$.</p>
<hr>
<p>So if over half the numbers $\{1,2,\cdots,n-1\}$ are Fermat witnesses for composite $n$, we can say that the chance of $n$ being returned prime after $k$ Fermat Primality Tests is usually at most $\left(\frac{1}{2}\right)^k \rightarrow 0$ as we increase $k$. Or better, $n$ is returned accurately composite with probability at least $1 - \left(\frac{1}{2}\right)^k \rightarrow 1$. </p>
<p>Some things to note here:</p>
<ol>
<li>We&#39;re using the phrase &quot;...with probability...&quot; loosely here, since either a number is composite or not; primality is deterministic. Probability might be better replaced with &quot;confidence&quot; or &quot;our belief that...&quot;. After $k$ tests, <em>we believe with confidence</em> $1 -\left(\frac{1}{2}\right)^k$ that $n$ is prime. If a number is actually prime, it will always pass Fermat&#39;s test, no matter how many times you run it, but we don&#39;t have that knowledge beforehand when running the tests.</li>
<li>Our bound on the number of Fermat witnesses relied on there being at least 1 Fermat witness $a$ with $\gcd(a,n) = 1$. There are unfortunately numbers that are not prime that also do not have Fermat witnesses. These are called <a href="https://en.wikipedia.org/wiki/Carmichael_number"><strong>Carmichael numbers</strong></a>, and gives us either a need to supplement this test further, or just leave a bit of room for doubt with these strong false positives.</li>
</ol>
<h3 id="other-tests">Other Tests</h3>
<p>We&#39;ve gone in-depth on one test, but it&#39;s worth mentioning that primality tests are still important and relevant topics in number theory. A more updated version of a Fermat-type test is found in the <a href="https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test"><strong>Miller-Rabin test</strong></a> which uses theories of <a href="https://en.wikipedia.org/wiki/Quadratic_reciprocity">quadratic reciprocity</a>, and a polynomial-time algorithm was found a little while ago with the <a href="https://en.wikipedia.org/wiki/AKS_primality_test"><strong>AKS primality test</strong></a>.</p>
<h3 id="different-types-of-primes">Different Types of Primes</h3>
<p>Another approach that is perhaps the most common one today is instead of checking and calculating <em>every</em> odd number&#39;s primality, we check only certain <strong>forms of primes</strong>. This is usually not an exhaustive method and will skip over some primes, but we get the benefit of finding the primes much quicker with specialized tests. Some types of primes include:</p>
<ul>
<li><strong>Mersenne primes</strong> are of the form $2^n - 1$ for an integer $n$</li>
<li><strong>Fermat primes</strong> are of the form $2^{2^n} - 1$ for an integer $n$</li>
<li>$p$ is a <strong>Sophie Germain prime</strong> if $2p+1$ is also prime.</li>
</ul>
<p>Mersenne primes have been of particular interest throughout history, with odd <a href="https://www.youtube.com/watch?v=T0xKHwQH-4I&amp;t=346s">facts about them even involving perfect numbers</a>. There of modern interest because we can efficiently test their primality, and as such this class of primes has held many records for being the largest known prime (contrasted with the faster growing Fermat primes, of which only 5 are known).</p>
<p>One of the faster tests available for Mersenne primes appears in a bit of a surprising way.</p>
<p><strong>Lucas-Lehmer Primality Test:</strong> Let $M_p = 2^p - 1$ be the Mersenne number we want to test, with $p$ an odd prime*. Define the sequence $s_n = s_{n-1}^2 - 2$ with $s_1 = 4$. Then $M_p$ is prime if and only if $s_{p-1} \equiv 0 \bmod M_p$.</p>
<p><strong>Proof:</strong> Many proofs of the correctness of this test are fairly lengthy and tedious. So, I&#39;m going to default to linking the <a href="https://fermatslibrary.com/s/a-really-trivial-proof-of-the-lucas-lehmer-test">group-theoretic proof</a> which I find more enlightening than the others (a proof, I might add, which uses group theory in the loosest sense, using results which can be learned in 5-10 minutes from scratch).</p>
<p>*we let $p$ be an odd prime since if $p=ab$ is composite, then $2^p - 1$ is composite:</p>
<center>
$2^p - 1 = (2^{a})^b - 1 = (2^a - 1)\left(1 + 2^a + (2^a)^2 + \cdots + (2^a)^{b-1} \right)$
</center>

<h3 id="prime-generating-formula">Prime Generating Formula</h3>
<p>In fact, it is possible to write a closed formula for such a prime test $\Phi(n)$ using some of our criteria above. Here&#39;s one using Wilson&#39;s theorem:</p>
<center>

$\begin{align} \Phi(n) = \left\lfloor \frac{(n-1)! \bmod n }{n-1} \right\rfloor \cdot n \end{align}$

</center>

<p>This isn&#39;t anything we haven&#39;t talked about: the floor of that division is essentially just using our inefficient Wilson&#39;s theorem based test to return 1 or 0 if $n$ is prime or not, then multiplying by $n$ so that the function actually returns $n$ if it is prime.</p>
<p>But we can do a bit better. We can remove the modular arithmetic, and make it such that instead of $\Phi(n)$ checking if $n$ is prime, make it such that $\Phi(n)$ returns the $n^\textrm{th}$ prime. The below is called <strong>Willans&#39; Formula</strong>:</p>
<center>

$\begin{align} \Phi(n) = 1 + \sum_{i=1}^{2^n} \left\lfloor \left( \frac{n}{\sum_{j=0}^{i} \left\lfloor \cos^2 \left( \frac{(j-1)! + 1}{j} \pi \right) \right\rfloor }  \right)^{1/n} \right\rfloor \end{align}$

</center>

<p>As you can probably guess just by looking at it, this isn&#39;t all that much more efficient, and the instance of $\frac{(j-1)! + 1}{j}$ should tell you that this is still just Wilson&#39;s theorem doing the work under the hood. There&#39;s a few more tricks invovled that we&#39;ll discuss later, but if you want the whole explanation of the mechanisms behind the formula, see <a href="https://www.youtube.com/watch?v=j5s0h42GfvM">this video</a>.</p>
<h2 id="sieves-and-filters">Sieves and Filters</h2>
<p>So far, we&#39;ve gone through and talked about simultaneously very interesting yet shallow results on prime numbers. We&#39;ve barely scratched the surface in just how important primes are, as we&#39;ve mostly stuck to readily calculable, number theory results, even of which we&#39;ve only touched a handful. Even in this post, I&#39;ve tried avoiding group theory for the sake of accessibility. But I hope all so far has illuminated that we shouldn&#39;t shy away from the mysteries of the primes, for there is much we can say about them.</p>
<p>But that&#39;s isn&#39;t to say that these problems and questions are easily solved (if they <em>can</em> be solved at all). I mean, just take a look at some of our previous prime tests. You would never come up with some of these tests just by investigating numbers—I wouldn&#39;t have. They all managed to be byproducts of more dense, abstract results that hide their applications unless one to be studying the right things at the right time. Even now, the Lucas-Lehmer test&#39;s group theory proof is merely a verification of correctness; the proof I like and understand best gives no insight into how one might have actually discovered that test for Mersenee primes.</p>
<p>So, let&#39;s take a step back in our quest to discover more prime numbers, and begin from the very start. How would you, say in elementary or middle school, <strong>try to test if a number is prime?</strong></p>
<p>It&#39;s exactly as we suggested first: let&#39;s just try and divide the number and see if we can factorize it; we take a big number and see if we can reduce it to a product of smaller numbers. But what if we instead did the reverse? What if instead of checking big numbers, why don&#39;t we instead <em>build up</em> from smaller numbers, and eliminate composite numbers that way? We know that 2 is prime, but anything that is a multiple of 2 definitely isn&#39;t prime. Same with 3. 4 is a multiple of 2, so we can skip that.</p>
<p>This inspires a nice little algorithm to filter primes from a list:</p>
<p><strong>Sieve of Eratosthenes:</strong> To find the prime numbers less than $n$, do the following:</p>
<ol>
<li>Keep track of 3 different list of numbers: <code>prime</code>, <code>composite</code>, <code>unmarked</code>. Everything (except 1) starts as <code>unmarked</code>.</li>
<li>Find the least <code>unmarked</code> number $p$.</li>
<li>Add every multiple of $p$ less than $n$ to the <code>composite</code> list, and remove them from <code>unmarked</code>.</li>
<li>Add $p$ to <code>prime</code> and remove it from <code>unmarked</code>.</li>
<li>Repeat Steps 2–4 until <code>unmarked</code> is empty.</li>
</ol>
<!-- ![Sieve of Eratosthenes Animation](/img/prime-number-theorem/sieve_eratosthenes.svg) -->
<iframe src="/img/prime-number-theorem/sieve_eratosthenes.svg" width="760" height="760" frameborder="0"></iframe>


<p>This can sound more complicated than it actually is, but it really is just the reverse idea of our trial divsion primality check. If a number $p$ is not a multiple of some prime less than it, it must be prime. We then can use that prime $p$ to find its multiples $pn$ and eliminate those as prime candidates. So first we find 2, and mark it prime, and then eliminate all the even numbers. The next number we find is 3, and eliminate all the multiples of 3. We eliminated 4 earlier with the evens, but then find 5 and remove the multiples of 5. We eliminated 6 with the evens (and again with the 3s), but get the chance to add 7 and remove the multiples of 7. (It turns out to eliminate all the composite numbers less than 100, we only need to eliminate all the multiples of $2,3,5,7$ since $11^2 &gt; 100$)</p>
<!-- add more on sieves -->
<p>Using <strong>sieves</strong> is a pretty common idea in number theory and combinatorics, since they give a concrete method to count, or at the very least <em>give an upper bound</em> for sizes of sets. They don&#39;t necessarily need to count primes like we did before, since they just need to be able to &quot;sift out&quot; or &quot;filter&quot; the elements we don&#39;t care, and this forms the basis for many proofs. But we&#39;ll come back to this point later.</p>
<p>For now, what the old Sieve of Eratosthenes should help visualize is why it&#39;s so hard to find primes. Only 25 numbers between 1–100 are prime. Only 168 are prime between 1–1000. As we increase the amount of numbers we look at, it becomes increasingly harder for a given $n$ to be prime; $n$ has to be able to dodge being a multiple of so many previous primes before it. Even just 2 being a prime reduces our potential candidate list in half. 3 being prime removes another sixth of our candidates, and so on. Primes just naturally get rarer, and so it shouldn&#39;t be that strange searching for larger and larger primes become incerasingly challenging. Can we quantify this rarity in primes?</p>
<h3 id="probability-of-being-prime">Probability of Being Prime</h3>
<p>One intuitive notion I think the Sieve of Eratosthenes shows really well is the idea of how divisibility translates to &quot;probability&quot;. What is the probability a number is even? Well, every other number is divisible by 2, and we eliminate those in our sieve. How about being divisble by 3? Well, that seems like that should be with probability $\frac{1}{3}$. What about being divisble by 7789, for <strong>large enough $n$</strong>, you&#39;d expect $\frac{1}{7789}$ to be divisible.</p>
<p>This thought can give us a way to think about the probability of being prime too. What does it mean for $n$ to be prime? Well, as our sieve describes, $n$ being prime should be equivalent to $n$ not being divisible by any prime less than it. We&#39;ll let $f(n) = \mathbb{P}(n \ \textrm{is prime})$, so we want to find</p>
<center>

$\displaystyle f(n) = \mathbb{P}(n \ \textrm{is prime}) \approx \prod_{p&lt;n \ \textrm{prime}} \mathbb{P}(p \ \textrm{not dividing} \ n)$

</center>

<p>If the probability of being divisible by $p$ is $\frac{1}{p}$, then being not divisible by $p$ should have probability $1-\frac{1}{p}$.</p>
<center>

$\displaystyle f(n) \approx \prod_{p&lt;n \ \textrm{prime}} \left( 1 - \frac{1}{p} \right) $

</center>

<p>This estimate is nice enough, but what we care more about this function is how it changes; can we relate the primality of $n$ to $n+1$? Well, since our product only includes primes, the only way the product changes is if $n$ is prime or not. If $n$ is prime, well that&#39;s a new prime to consider $n+1$ not being divisible by, and if $n$ is not prime, then that doesn&#39;t affect our product (ignore the fact that $n \nmid n+1$, we&#39;re only looking for a heuristic argument right now).</p>
<center>

$$
\begin{align}
f(n+1) &amp; \approx \prod_{p&lt;n+1 \ \textrm{prime}} \left( 1 - \frac{1}{p} \right) \\
% &amp; = \prod_{p&lt;n \ \textrm{prime}} \left( 1 - \frac{1}{p} \right) \cdot \begin{cases} 1-\frac{1}{n} &amp; \textrm{if} \ n \ \textrm{is prime} \\ 1 &amp; \textrm{if} \ n \ \textrm{is not prime} \end{cases}
&amp; = \prod_{p&lt;n \ \textrm{prime}} \left( 1 - \frac{1}{p} \right) \cdot \mathbb{P}(n \ \textrm{is not a prime divisor of} \ n+1) \\
&amp; = f(n) \cdot (1 - \mathbb{P}(n \ \textrm{is a prime divisor of} \ n+1)) \\
&amp; = f(n) \cdot \left(1 - \mathbb{P}(n \ \textrm{is a prime}) \cdot \mathbb{P}(n \ \textrm{divides} \ n+1) \right) \\
&amp; = f(n) \cdot \left(1 - f(n) \cdot \frac{1}{n} \right) \\
\end{align}
$$

</center>

<p>Rearranging a little bit, we get that</p>
<center>

$\displaystyle f(n+1) - f(n) \approx -\frac{(f(n))^2}{n}$

</center>

<p>If $f(n)$ is a nice enough function, we can approximate further that </p>
<center>

$\displaystyle f&#39;(n) \approx f(n+1) - f(n) \approx -\frac{(f(n))^2}{n}$

</center>

<p>We can solve this differentiable equation, giving us</p>
<center>

$\displaystyle -\frac{f&#39;(n)}{(f(n))^2} = \frac{1}{n} \Rightarrow f(n) = \frac{1}{\ln(cn)}$

</center>

<hr>
<p>Tying things together, note by our Euler Product Formula for the Riemann zeta function, we could also have done this rough derivation with</p>
<center>

$\displaystyle \frac{1}{f(n)} \approx \prod_{p&lt;n \ \textrm{prime}} \left(\frac{1}{1 - \frac{1}{p}} \right) \approx \sum_{k=1}^{n} \frac{1}{k} \approx \ln(n)$

</center>


<hr>
<p>Perhaps to make it clearer, if the probability of being prime is roughly $\frac{1}{\ln(n)}$, then there are roughly $\pi(n) \approx \frac{n}{\ln(n)}$ many primes less than $n$ ($\pi(n)$ is often used to denote the <strong>prime-counting function</strong>, and give the number of primes less than $n$).</p>
<p>Although we only used rough estimates, we ended up with a result that formalizes our intuition that it becomes more difficult and unlikely for larger numbers to be prime. But also note that by our treatment of what &quot;the probability of being prime&quot; means,</p>
<center>

$\displaystyle f(n) = \mathbb{P}(n \ \textrm{is prime}) = \mathbb{P}(\textrm{has no prime divisor} \ p&lt;n)$

</center>

<p>all numbers less than $n$ should have the same probability of not having a prime divisor less than $p&lt;n$—after all, we treated our probability of not having a divisor $p$ as $\frac{1}{p}$ which only depends on $p$, not $n$, formalizing the idea of &quot;dodging&quot; being in the fraction of numbers that are a multiple of $p$. So a more accurate statement is that the <em>fraction of numbers that are prime from 1–$n$ is proportional</em> to $\frac{1}{\ln(n)}$. If this is unclear why we specify this, just imagine we include prime divisors $p&gt;n$. Even though it&#39;s impossible for $p \mid n$ with $p&gt;n$, our intuition of not being in the fraction of numbers that are mulitiples of $p$ would have us include an additional factor of $1-\frac{1}{p}$ in our product. This obviously lowers our probability just by considering a wider range of numbers that &quot;miss&quot; dividng $n$, but in actuality have no impact on the actual prime-ness of $n$ (what we&#39;ve stumbled upon for formalizing probability is known as <a href="https://en.wikipedia.org/wiki/Natural_density">natural density</a>).</p>
<p>With this in mind, let&#39;s keep moving forward where we&#39;ll later do this with the rigor it deserves.</p>
<hr>
<p>It should be noted that weirdly enough, as nice as this intuitive argument is, it is actually just techincally, barely wrong. In reality,  the asymptotics we&#39;ve been studying actually look like</p>
<center>

$\displaystyle f(n) \approx \prod_{p&lt;n \ \textrm{prime}} \left(1 - \frac{1}{p} \right) \approx \frac{1}{e^{\gamma} \ln(n)}$

</center>

<p>where $\gamma$ is the <a href="https://en.wikipedia.org/wiki/Euler%27s_constant">Euler–Mascheroni constant</a>. I don&#39;t have a good answer why this is the case and what our argument misses besides the fact that we worked with estimates and assumed independence of of divisibility.</p>
<!-- But let's clear up exactly what we meant by "probability of being prime". Using our Sieve of Eratosthenes, we are considering how many integers in 1–$n$ dodge being a multiple of all the primes less than $n$. So in our loose definition of what the probability of being prime means, we are saying that approximately the fraction of numbers that are prime in the range 1–$n$ is $\frac{1}{\ln(n)}$. -->
<h2 id="distributions-and-the-prime-number-theorem">Distributions and the Prime Number Theorem</h2>
<p>With our first little idea in the works that primes are approximately logarithmically distributed, we now look for some more precise results on how the primes are distributed.  </p>
<h3 id="bertrand-s-postulate">Bertrand&#39;s Postulate</h3>
<p>Perhaps one of the earliest and most well-known distribution results we have is Bertrand&#39;s Postulate. Due to the logarithmic nature we&#39;ve found, it shouldn&#39;t be surprising that this result involves a multiplicative range instead of an arithmetic one:</p>
<p><strong>Bertrand&#39;s Postulate:</strong> $\forall n \geq 2,  \ \exists p \ \textrm{prime s.t.} \ n&lt;p&lt;2n$</p>
<p>This doesn&#39;t necessarily say this is the smallest guaranteed interval to find a prime, nor does it say this interval generates a unique prime (for example, 7 satisfies the Postulate for both $n=4,5$). Nonetheless, it characterizes that feeling of having to expand our search for primes to greater ranges of integers. But what about the range $[n,2n]$ necessitates a prime being there?</p>
<hr>
<p><strong>Proof (Erdős):</strong> Before we get into the proof, we are first going to want to play around with what will become our key guide towards the proof. Consider</p>
<center>

$\displaystyle {2n \choose n} = \frac{(2n)!}{(n!)^2}$

</center>

<p>If you try factoring this for a few values of $n$, something apparent appears. For example, here&#39;s the factorization for $n=22$.</p>
<center>

$\displaystyle {2\cdot 22 \choose 22} = 2^3\cdot 3 \cdot5 \cdot 13 \cdot \color{red}{23} \cdot \color{red}{29} \cdot \color{red}{31} \cdot \color{red}{37} \cdot \color{red}{41} \cdot \color{red}{43}$

</center>

<p>It seems that $2n \choose n$ contains all prime factors between $n$ and $2n$ once, and no prime factor greater $2n$. We&#39;re going to try and use that fact to bound $2n \choose n$ appropriately to show that there needs to be at least one prime factor in $[n,2n]$ for it to be not too small and not too large. If we&#39;re going to talk about its factorization via how large it is, let&#39;s start to find some inequalities. </p>
<p><strong>Lemma 1:</strong> $ \ \displaystyle \frac{4^n}{2n} \leq {2n \choose n}$ </p>
<p><strong>Proof:</strong> $4^n = (1+1)^{2n} = \sum_{k=0}^{2n} {2n \choose k} = 2 + \sum_{k=1}^{2n-1} {2n \choose k} \leq 2n \cdot {2n \choose n}$. The last inequality comes from the middle binomial coefficient being the greatest. $\ \blacksquare$</p>
<p>Next, it seems natural we should understand the prime factorization of factorials. Let $R_p(n)$ be the largest exponent such that for a prime $p$, $p^R \mid n$ (note for <em>any</em> prime $p$; it might be that $R_p(n) = 0$). We are interested in $R_p({2n \choose n})$.</p>
<p><strong>Lemma 2:</strong> For any prime $p$ and $R = R_p({2n \choose n})$, $ \ \displaystyle p^R \leq 2n$.</p>
<p><strong>Proof:</strong> There&#39;s a nice <a href="https://en.wikipedia.org/wiki/Legendre%27s_formula">formula</a> (due to Legendre) that gives </p>
<center>

$\displaystyle R_p(n!) = \sum_{i=1}^{\infty} \left\lfloor \frac{n}{p^i} \right\rfloor$

</center>

<p>If this is not obvious, the idea is that you count how many multiples of $p,p^2,p^3,\cdots$ appear from $1$ to $n$, and each occurrence contributes 1 to the exponent $R$ (it&#39;s only one contribution even for $p^2,p^3,\cdots$ since we already count each of the factors previously i.e. $p^2$ is a multiple of $p$ as well). Further, if $p^i &gt; n$, then the $\left\lfloor \frac{n}{p^i} \right\rfloor$ reduces to 0 so we don&#39;t count powers of primes that don&#39;t divide $n!$.</p>
<p>Back to the problem at hand, since we&#39;re considering the division of two factorials, $R = R_p({2n \choose n})$ gains contributions from powers of $p$ in $(2n)!$ and loses powers from the division of powers of $p$ in $(n!)^2$. Hence,</p>
<center>

$\displaystyle R = \sum_{i=1}^{\infty} \left\lfloor \frac{2n}{p^i} \right\rfloor - 2\sum_{i=1}^{\infty} \left\lfloor \frac{n}{p^i} \right\rfloor = \sum_{i=1}^{\infty} \left( \left\lfloor \frac{2n}{p^i} \right\rfloor - 2\left\lfloor \frac{n}{p^i} \right\rfloor \right)$

</center>

<p>It&#39;s not hard to see (if you want, just graph it) that the only values of this final sum&#39;s terms are</p>
<center>

$\displaystyle \left\lfloor \frac{2n}{p^i} \right\rfloor - 2\left\lfloor \frac{n}{p^i} \right\rfloor = \begin{cases} 0 &amp; \textrm{if} \ \left\lfloor \frac{n}{p^i} \right\rfloor \bmod 1 &lt; \frac{1}{2} \\ 1 &amp; \textrm{if} \ \left\lfloor \frac{n}{p^i} \right\rfloor \bmod 1 \geq \frac{1}{2} \end{cases}$

</center>

<p>(This essentially checks if doubling $n$ to $2n$ has room for another multiple of $p^i$ beyond the expected contributions in the ranges of length $n$). Alternatively, notice that each term is an integer, and</p>
<center>

$\displaystyle \left\lfloor \frac{2n}{p^i} \right\rfloor - 2\left\lfloor \frac{n}{p^i} \right\rfloor &lt; \frac{2n}{p^i} - 2\left( \frac{n}{p^i} - 1 \right) = 2$

</center>

<p>Further, this term is all 0 when $p^i &gt; 2n$ i.e. $i &gt; \log_p(2n)$ by the floor function. So, $R \leq \log_p(2n)$ and thus $p^R \leq p^{\log_p(2n)} = 2n$. $ \ \blacksquare$</p>
<hr>
<p>Already, we can deduce quite a lot of information about the number of primes that divide $2n \choose n$. Using our two lemmas, let $p_1,\cdots,p_\ell$ be the primes dividing $2n \choose n$. Then</p>
<center>

$\displaystyle \frac{4^n}{2n} \leq {2n \choose n} = \prod_{i = 1}^\ell p_i^{R_p({2n \choose n})} \leq \prod_{i = 1}^\ell 2n = (2n)^\ell$

</center>

<p>Taking logarithms, we get that $\ell \geq \frac{2n \log(2)}{\log(2n)} - 1$, giving a lower bound on <em>how many</em> primes must divide $2n \choose n$. Also, it is clear that no prime dividing ${2n \choose n}$ can be greater than $2n$ (check Legendre&#39;s formula if needed) and so in particular this gives us an upper bound on $\pi(2n)$ the number of primes less than or equal to $2n$.</p>
<hr>
<p><strong>Lemma 3:</strong> If $p$ is an odd prime and $\frac{2n}{3} &lt; p \leq n$, then $R_p({2n \choose n}) = 0$.</p>
<p><strong>Proof:</strong> $(2n)!$ contains two factors of $p$ via $p$ and $2p$. $(n!)^2$ also contains two factors of $p$. These factors cancel in ${2n \choose n}$. The bound ensures that $3p &gt; 2n$ cannot appear in the numerator to contribute more factors (and it being odd makes it so that $2p$ doesn&#39;t contribute more than expected). $\blacksquare$</p>
<p>It&#39;s also easy to see by similar reasoning that for prime $p$:</p>
<ul>
<li>if $n&lt;p\leq 2n$, then $R_p({2n \choose n}) = 1$</li>
<li>if $p &gt; 2n$, then $R_p({2n \choose n}) = 0$</li>
</ul>
<p>These will be useful later. Finally, we need one more simpler bound before proving the Postulate. We&#39;ll introduce one last piece of notation for the <strong>primorial</strong>.</p>
<center>

$\displaystyle n\# = \prod_{p \leq n \ \textrm{prime}} p$

</center>

<p>It&#39;s essentially $n!$ but only looking at primes less than $n$ as opposed to all integers less than $n$.</p>
<p><strong>Lemma 4:</strong> For $n\geq 1$, $n\# &lt; 4^n$.</p>
<p><strong>Proof:</strong> We&#39;ll do this by induction, checking even and odd cases (the base cases are easy to check). Supoose this holds for up to $n-1$.</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <strong>(Even)</strong> Say $n$ is even i.e. $n=2k$. Since $2k$ is composite, then by the inductive hypothesis,</p>
<center>
$(2k)\# = (2k-1)\# &lt; 4^{2k-1} &lt; 4^{2k}$
</center>

<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <strong>(Odd)</strong> Say $n$ is odd i.e. $n=2k+1$, and consider </p>
<center>

<!-- $\displaystyle {2k+1 \choose k} = \frac{(2k+1)!}{k!(k+1)!} > \prod_{i=k}^{2k} i > \prod_{\textrm{prime} \ k+2 \leq p \leq 2k+1} p = \frac{(2k+1)\\#}{(k+1)\\#}$  -->
$\displaystyle {2k+1 \choose k} = \frac{(2k+1)!}{k!(k+1)!} &gt; \prod_{\textrm{prime} \ k+2 \leq p \leq 2k+1} p = \frac{(2k+1)\#}{(k+1)\#}$ 

</center>

<p>We get the inequality since the binomial coefficient is an integer, with all the prime factors between $k+2$ and $2k+1$ dividing it since they divide the numerator but not the denominator. These relations get us close to allowing use of our inductive hypothesis.</p>
<center>

$\begin{align} 
(2k+1)\# &amp; = (k+1)\# \cdot \frac{(2k+1)\#}{(k+1)\#} \\
&amp; &lt; 4^{k+1} \cdot {2k+1 \choose k} \\
&amp; &lt; 4^{k+1} \cdot 2^{2k} \\
&amp; = 4^{2k+1}
\end{align}$ 

</center>

<p>We get the last inequality by noting that $\sum_{i=0}^{2k+1} {2k+1 \choose i} = 2^{2k+1}$ and ${2k+1 \choose k} = {2k+1 \choose k+1}$ since $2k+1$ is odd. So ${2k+1 \choose k} &lt; \frac{1}{2} 2^{2k+1} = 2^{2k}$. $\ \blacksquare$</p>
<p><strong>Proof of Bertrand&#39;s Postulate:</strong> Say this is false, and let $n \geq 3$ be such a counterexample with no prime $p$ in the interval $n &lt; p &lt; 2n$. Note by our lemmas, there are no prime factors $p$ of $2n \choose n$ such that:</p>
<ul>
<li>$2n &lt; p$ as such a factor must divide $(2n)!$</li>
<li>$p = 2n$ since $2n$ is even</li>
<li>$n&lt;p&lt;2n$ by assumption</li>
<li>$\frac{2n}{3} &lt; p \leq n$ by <strong>Lemma 3</strong></li>
</ul>
<p>So all prime factors of $2n \choose n$ must be $p \leq \frac{2n}{3}$. So we can simplify the prime factorization to be</p>
<center>

$\displaystyle {2n \choose n} =  \prod_{\textrm{prime } p} p^{R} = \prod_{p \leq \frac{2n}{3}} p^{R}$

</center>

<p>But also, if $p &gt; \sqrt{2n}$, then ${2n \choose n}$ has at most one factor of $p$ (since $p^2 &gt; 2n$ and can&#39;t divide $(2n)!$ i.e. see Lemma 2). So, if we can further simplify our prime factorization for that interval</p>
<center>

$\displaystyle {2n \choose n} = \prod_{p \leq \frac{2n}{3}} p^{R} = \left( \prod_{p \leq \sqrt{2n}} p^{R} \right) \left(\prod_{\sqrt{2n} &lt; p \leq \frac{2n}{3}} p^{R} \right) \leq \left( \prod_{p \leq \sqrt{2n}} p^{R} \right) \left(\prod_{\sqrt{2n} &lt; p \leq \frac{2n}{3}} p^{1} \right)$$

</center>

<p>Using <strong>Lemma 2</strong>, we can bound $p^R \leq 2n$. Also, obviously, there can only be at most $\sqrt{2n} - 1$ distinct prime numbers less than or equal to $\sqrt{2n}$ (there are only that many integers less than $\sqrt{2n}$ excluding 1, after all). Starting with <strong>Lemma 1</strong> and ending with <strong>Lemma 4</strong>, we can combine all of this into one final inequality.</p>
<center>

$\begin{align} 
\frac{4^n}{2n} \leq {2n \choose n} &amp; \leq \left( \prod_{p \leq \sqrt{2n}} p^{R} \right) \left(\prod_{\sqrt{2n} &lt; p \leq \frac{2n}{3}} p \right) \\
&amp; \leq (2n)^{\sqrt{2n} - 1} \prod_{p \leq \frac{2n}{3}} p \\
&amp; &lt; (2n)^{\sqrt{2n} - 1} 4^{2n/3} \\
\end{align}$

</center>

<p>Rearranging a little bit more, we end with the inequality</p>
<center>

$\displaystyle 4^{n/3} \leq (2n)^{\sqrt{2n}} \Rightarrow 2^{\sqrt{2n}} \leq (2n)^3$

</center>

<p>This inequality fails for $n&gt;427$, giving us our contradiction that we needed. Hence, we have shown Bertrand&#39;s Postulate is true for $n&gt;427$. </p>
<p>To show it for $n\leq 426$, this is small enough that we don&#39;t need to do anything hard; we can just find a set of primes that work for all desired intervals. Consider the list</p>
<center>

$3,5,7,13,23,43,83,163,317,631$

</center>

<p>This sequence of primes are chosen to be such that the next prime in the sequence is the largest prime less than twice the previous. We don&#39;t need to know all the primes less than 427 and check every case of $(n,2n)$, since these give us all the examples we need!</p>
<center>
$\blacksquare$
</center>

<hr>
<p>Despite its simplicity, the impact of Bertrand&#39;s Postulate can be found in many results. For example, it gives a simple bound on prime gaps: if you have a prime $p$, you know you only have to search up to $2p$ before you find your next prime. However, these types of bounds are rarely obvious.</p>
<p><strong>Legendre&#39;s Conjecture (Unsolved):</strong> $\forall n \geq 2,  \ \exists p \ \textrm{prime s.t.} \ n^2&lt;p&lt;(n+1)^2$.</p>
<p>Note that $(n+1)^2 \leq 2n^2$ for $n&gt;2$, so we can&#39;t solve this using Bertrand&#39;s postulate. This is not to say there have not been improvements, however:</p>
<p><strong>Nagura (1952):</strong> $\forall n \geq 25,  \ \exists p \ \textrm{prime s.t.} \ n&lt;p&lt;\frac{6}{5}n$</p>
<p>Getting hard, concrete bounds like this are rarely tangible, as the insight necessary to get an object to analyze is quite demanding. Even for the above proof, it is not totally obvious that the point of investigation begins at binomial coefficients. With the major result of the Prime Number Theorem at the end, we will obtain asymptotic bounds to shrink this interval as much as we want.</p>
<p>Here&#39;s another interesting consequence of Bertrand&#39;s postulate:</p>
<!-- https://www3.nd.edu/~dgalvin1/pdf/bertrand.pdf -->
<p><strong>Claim:</strong> The set $\{1,2,3,\cdots,2n\}$ can be partitioned into pairs $\{a_1,b_1\}$, $\{a_2,b_2\}$, $\cdots$, $\{a_n,b_n\}$ so that for all pairs $a_i + b_i$ is prime.</p>
<p><strong>Proof:</strong> We use induction.</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <strong>Base Case:</strong> $n = 1$ works as $1+2=3$ is prime. </p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <strong>Inductive Step:</strong> Say we can find such a partitioning for any set of even size less than $2n$. By Bertrand&#39;s Postulate, there is a prime $2n &lt; p &lt; 4n$, i.e. there is a prime of the form $p = 2n + m$ for $1 \leq m &lt; 2n$ (note $m$ must be odd). We can now pair off some numbers in the set by</p>
<center>

$\displaystyle \left\{2n,m \right \},\{2n-1,m+1\},\{2n-2,m+2\},\cdots,\left \{n + \left\lceil \frac{m}{2} \right\rceil, n + \left\lfloor \frac{m}{2} \right\rfloor \right \}$

</center>

<p>with every pair summing to $p$. These pairs take care of the numbers $\{m,m+1,\cdots,2n\}$. The remaining set of $\{1,2,\cdots,m-1\}$ can be partitioned by the inductive hypothesis (since $m-1 &lt; 2n$ is even). $\ \blacksquare$</p>
<p>Also, we can chain intervals together if we want to find lots of distinct primes. I.e. if we look in the intervals $[1,2]$, $[2,4]$, $[4,8]$, etc., because each interval picks up exactly where the last one left off, we can find as many distinct primes as intervals we&#39;re willing to check. In fact, we&#39;ve already briefly seen this trick used once in Willan&#39;s formula:</p>
<center>

$\begin{align} \Phi(n) = 1 + \sum_{i=1}^{\color{red}{2^n}} \left\lfloor \left( \frac{n}{\sum_{j=0}^{i} \left\lfloor \cos^2 \left( \frac{(j-1)! + 1}{j} \pi \right) \right\rfloor }  \right)^{1/n} \right\rfloor \end{align}$

</center>

<p>The $2^n$ ensures we find <em>at least</em> $n$ distinct primes as we check the intervals $[1,2]$, $[2,4]$, $[4,8]$, etc. This guarantee of finding new primes in these intervals lends itself quite nicely to prime generation, even if in unexpected ways:</p>
<p><strong>Wright&#39;s Prime Generating Formula:</strong> There&#39;s a value of $\alpha \in (1,2)$ such that </p>
<center>

$\displaystyle \left\lfloor 2^\alpha \right\rfloor, \left\lfloor 2^{2^\alpha} \right\rfloor, \left\lfloor 2^{2^{2^\alpha}} \right\rfloor, \cdots$

</center>

<p>are all prime. (The value <a href="https://www.jstor.org/stable/2306356">Wright originally gave</a> was $\alpha \approx 1.929$)</p>
<p><strong>Proof:</strong> Just to be clear, what we&#39;re exactly saying is that there&#39;s a value $\alpha$ such that for the recurrence</p>
<center>

$\displaystyle g_0 = \alpha, \ \ \ g_{n+1} = 2^{g_n}$

</center>

<p>we have $\left\lfloor g_n \right\rfloor$ is prime. The idea is that we want to bound $p_n &lt; g_n &lt; p_n + 1$, which leads naturally to trying to find our constant $\alpha$ in between the repeated <em>logarithms</em> of $p_n$ and $p_n + 1$. We can ensure such a constant exists by picking primes that are spaced far enough away—hence Bertrand&#39;s Postulate—that will help create a sequence that converges to $\alpha$. </p>
<p>So, first we choose a sequence of primes $p_n$ such that</p>
<ul>
<li>$p_1 = 2$ or $3$,</li>
<li>$2^{p_n} &lt; p_{n+1} &lt; p_{n+1} + 1 &lt; 2^{p_{n} + 1}$ </li>
</ul>
<p>We know we can choose such a sequence of primes thanks to Bertrand&#39;s Postulate. These will be the primes our magic sequence $\lfloor g_n \rfloor$ will generate. Taking the $\log_2$ (from here on, $\log$ will refer to $\log_2$) of this inequality, we find that</p>
<center>

$\displaystyle p_n &lt; \log(p_{n+1}) &lt; \log(p_{n+1} + 1) &lt; p_{n} + 1$

</center>

<p>Now we define two more sequences:</p>
<center>

$\displaystyle u_n = \log^{(n)} (p_n) \ \ \ \ \ \ \ \ \  v_n = \log^{(n)}(p_n + 1)$

</center>

<p>where $\log^{(n)} (x) = \overset{\textrm{n times}}{\overline{\log(\log(\cdots \log}}(x) \cdots ))$ i.e. the $n$-fold composition of $\log$ with itself. By taking further $\log$ of our inequalities $n$ times, we get that</p>
<center>

$\displaystyle u_{n} &lt; u_{n+1} &lt; v_{n+1} &lt; v_{n}$

</center>

<p>$u_{n}$ is a bounded (by $v_1$) monotonically increasing sequence, and so it converges $u_n \rightarrow \alpha$. So we obtain that $u_n &lt; \alpha &lt; v_n$ ($v_n$ might converge to something else, but we know at least that all terms of $v_n$ must be greater than $\alpha$ or else it&#39;d contradict our inequalities above).</p>
<p>By letting $g_0 = \alpha$, and $g_{n+1} = 2^{g_n}$ as described, and repeatedly raising our inequalities to the power 2, we then get</p>
<center>

$\displaystyle u_{n} &lt; \alpha &lt; v_{n} \Rightarrow p_n &lt; g_n &lt; p_n + 1$

</center>

<p>Therefore, $\lfloor g_n \rfloor = p_n$ and follows our sequence of primes. $\ \blacksquare$</p>
<hr>
<p>Actually <em>computing</em> such an $\alpha$ is not easy though. We&#39;ve shown the existence of such a number as the limit of a sequence, but finding that limit is quite hard. Even calculating approximations of $\alpha$ via $u_n$ is hard, since we need to <em>already have a sequence of primes</em> $p_n$ predetermined (so unfortunately, this isn&#39;t that useful for actually <em>generating</em> more primes, but at best generating numbers close to primes outside of our seqeuence). </p>
<p>But because it&#39;s sequence dependent, there are many such constants that serve our purpose. For instance, if we let</p>
<center>

$\displaystyle p_1 = 3, p_2 = 13, p_3 = 16381$

</center>

<p>we can find that it&#39;s corresponding $\alpha$ (which is also maximal) is about</p>
<center>

$\begin{align} 

\log(3) &amp; \approx 1.5849625 \\
\log(\log(13)) &amp; \approx 1.8876967 \\
\log(\log(\log(16381))) &amp; \approx 1.9287787 \\

\end{align}$

</center>

<p>If we instead choose a different sequence, like</p>
<center>

$\displaystyle p_1 = 2, p_2 = 5, p_3 = 37$

</center>

<p>we can find a different approximation:</p>
<center>

$\begin{align} 

\log(2) &amp; = 1 \\
\log(\log(5)) &amp; \approx 1.2153233 \\
\log(\log(\log(37))) &amp; \approx 1.2516476 \\

\end{align}$

</center>

<p>Also, if you like these power-towers and primes, we&#39;re quite lucky Bertrand&#39;s postulate finds a prime in $n &lt; p &lt; 2n$, as that also immediately means we can find primes in $n &lt; p &lt; 3n$, or in any range $n &lt; p &lt; Bn$. So really, we can generalize our theorem and proof quite easily to instead say:</p>
<p><strong>Claim:</strong> For all $B \geq 2$, there&#39;s a value of $\alpha$ such that </p>
<center>

$\displaystyle \left\lfloor B^\alpha \right\rfloor, \left\lfloor B^{B^\alpha} \right\rfloor, \left\lfloor B^{B^{B^\alpha}} \right\rfloor, \cdots$

</center>

<p>are all prime.</p>
<!-- can improve this B value to any (1+epsilon) with PNT -->
<h2 id="prime-number-theorem">Prime Number Theorem</h2>
<p>Bertrand&#39;s Postulate gave us a nice first step towards making precise how primes are distributed by giving us an upper bound on how frequently primes arise. Bringing things back around, Bertrand&#39;s Postulate also suggests that the number of primes grows at least logarithmically. Again, consider the intervals</p>
<center>

$\displaystyle (1,2]$, $(2,4]$, $(4,8],\cdots$

</center>

<p>We know there is at least 1 prime in each of these disjoint intervals, so we know that $p_n \leq 2^n$ where $p_n$ is the nth prime. Thus, if we let $\pi(x)$ be the prime-counting function from before, then we have that $\pi(x) \geq \log_2(x)$. Of course, this is not that close to our previous estimate with $\pi(x) \approx \frac{x}{\ln(x)}$, but it is an initial, definitive start beyond our heuristics to precisely describe the distribution of primes.</p>
<p>We can, however, bound $\pi(x)$ with just Bertrand&#39;s postulate in a promising way. From here on, $\log$ refers to the natural logarithm $\ln$. Recall from before that we found that </p>
<center>
$\displaystyle \pi(2n) \geq \frac{2n \log(2)}{\log(2n)} - 1 = \frac{2n}{\log(2n)}\left(\log(2) - \frac{\log(2n)}{2n} \right)$
</center>

<p>This, however, suffers from the fact that our proof only makes sense for integers $n$. If we want to extend this to all real numbers $x\geq 2$, we will need to work around it a bit more. Let $n=\lfloor x/2 \rfloor$, so $2n \leq x &lt; 2n+2$ and in particular $x - 2 &lt; 2n$.</p>
<center>
$\displaystyle \pi(x) \geq \pi(2n) \geq \frac{2n}{\log(2n)}\left(\log(2) - \frac{\log(2n)}{2n} \right) \geq \frac{x-2}{\log(x)}\left(\log(2) - \frac{\log(2n)}{2n} \right)$
</center>

<p>The function $\frac{\log(x)}{x}$ is maximized at $x=e$ with value $\frac{1}{e}$. Also, for $x\geq 4$, $x-2 \geq \frac{x}{2}$</p>
<center>
$\displaystyle \pi(x) \geq \frac{x-2}{\log(x)}\left(\log(2) - \frac{\log(2n)}{2n} \right) \geq \frac{x}{\log(x)} \cdot \frac{1}{2}\left(\log(2) - \frac{1}{e} \right)$
</center>

<p>So we have bounded from below $\pi(x)$ by $\frac{x}{\log(x)}$ up to a positive constant (one can just check that this also holds for $4 &gt; x\geq 2$). This bound is nowhere near optimal, but I tried giving a constant that was most readily calculable with less additional verification needed; we could give better bounds but have to check for smaller values manually, and or have seemingly arbitrary constants pop out of nowhere to verify later. We can also give a similar upper bound, but it will take a bit more work. First notice that</p>
<center>
$\displaystyle 4^n = \sum_{k=0}^{2n} {2n \choose k} \geq {2n \choose n} \geq \prod_{n \leq p \ \textrm{prime} \leq 2n} p \geq \prod_{n \leq p \ \textrm{prime} \leq 2n} n = n^{\pi(2n) - \pi(n)}$
</center>

<p>Again taking logarithms, we have</p>
<center>
$\displaystyle \pi(2n) - \pi(n) \leq \frac{n\log (4)}{\log (n)}$
</center>

<p>This is close to what we want, in that $\pi(2n) - \pi(n)$ counts the number of primes in the interval $(n,2n]$ of length $n$, but we want the number of primes in the interval $(0,n]$. And as before, to make this work for real numbers, our bounds have to a be a bit more careful. Let $n = \lfloor x \rfloor$ i.e. $n \leq x &lt; n+1$.</p>
<center>

$\begin{align}

\pi(2x)-\pi(x) &amp; \leq \pi(2(n+1)) - \pi(n) \\
&amp; = \big(\pi(2n+2) - \pi(2n) \big) + \big(\pi(2n) - \pi(n) \big) \\
&amp; \leq 2 + \frac{n \log(4)}{\log(n)} \\
&amp; = \frac{n}{\log(n)} \left( 2 \cdot \frac{\log(n)}{n} + \log(4)  \right) \\
&amp; \leq \frac{n}{\log(n)} \left( 2 \cdot \frac{1}{e} + \log(4)  \right) \\
&amp; \leq \frac{x}{\log(\sqrt{x})} \left(\frac{2}{e} + \log(4)  \right) \\
&amp; = \frac{x}{\log(x)} \cdot 2 \left(\frac{2}{e} + \log(4)  \right) \\

\end{align}$

</center>

<p>The only main point of interest is to recall that for $x\geq 3$, we have $n \geq x - 1 \geq \sqrt{x}$. We can now chain together exponentially decreasing intervals with a suitable cut-off to bound $\pi(x)$. Let $\ell$ be the greatest integer such that $x/2^\ell &gt; \sqrt{x}$. </p>
<center>

$\begin{align}

% \pi(x) = \left( \pi(x) - \pi \left(\frac{x}{2} \right) \right) + \left( \pi\left(\frac{x}{2^{2}} \right) - \pi\left(\frac{x}{2^{3}} \right) \right) + \cdots + \left( \pi\left(\frac{x}{2^{\ell}} \right) - \pi\left(\frac{x}{2^{\ell + 1}} \right) \right) + \pi\left(\frac{x}{2^{\ell + 1}} \right)

\pi(x) &amp; = \left( \pi(x) - \pi \left(\frac{x}{2} \right) \right) + \pi\left(\frac{x}{2} \right) \\
&amp; = \sum_{k=0}^{\ell} \left( \pi \left( \frac{x}{2^{k}} \right) - \pi \left( \frac{x}{2^{k+1}} \right)  \right) + \pi \left( \frac{x}{2^{\ell+1}} \right) \\
&amp; \leq \sum_{k=0}^{\ell} \left(  \frac{x/2^{k+1}}{\log\left(x/2^{k+1} \right)} \cdot c  \right) + \pi \left( \frac{x}{2^{\ell+1}} \right)


\end{align}$

</center>

<p>where $c$ is the constant found before. Now for all $k \leq \ell$, we have $x/2^k &gt; \sqrt{x}$ i.e. $\log\left(x/2^k \right) &gt; \frac{1}{2} \log(x)$.</p>
<center>

$\begin{align}

\pi(x) &amp; \leq \sum_{k=0}^{\ell} \left(  \frac{x/2^{k+1}}{\log\left(x/2^{k+1} \right)} \cdot c \right) + \pi \left( \frac{x}{2^{\ell+1}} \right) \\
&amp; \leq \sum_{k=0}^{\ell} \left(  \frac{x/2^{k+1}}{\frac{1}{2}\log(x)} \cdot c \right) + \pi \left( \frac{x}{2^{\ell+1}} \right) \\
&amp; = \frac{x}{\log(x)} \cdot c \cdot \sum_{k=0}^{\ell} \left(  \frac{1}{2^{k}} \right) + \pi \left( \frac{x}{2^{\ell+1}} \right) \\
&amp; \leq \frac{x}{\log(x)} \cdot c \cdot 1 + \pi \left( \frac{x}{2^{\ell+1}} \right) \\
&amp; \leq \frac{x}{\log(x)} \cdot c + \sqrt{x} \\
&amp; \leq \frac{x}{\log(x)} \cdot c + \frac{x}{\log(x)} \\
&amp; = \frac{x}{\log(x)}\left(c + 1 \right) \\
&amp; = \frac{x}{\log(x)}\left(\frac{4}{e} + 2\log(4) + 1 \right)

\end{align}$

</center>

<p>Recalling by construction that $x/2^{\ell+1} \leq \sqrt{x}$, and the trivial bound $\pi\left(x/2^{\ell+1}\right) \leq x/2^{\ell+1}$. We also used that $\log(x) \leq \sqrt{x}$ i.e. $\sqrt{x} \leq x/\log(x)$. All together, we have </p>
<center>

$\displaystyle \frac{x}{\log(x)} \left(\frac{1}{2}\log(2) - \frac{1}{2e} \right) \leq \pi(x) \leq \frac{x}{\log(x)}\left(\frac{4}{e} + 2\log(4) + 1 \right)$

</center>

<p>This gives some real, concrete motivation to pursue the Prime Number Theorem.</p>
<hr>
<h3 id="proof-of-the-prime-number-theorem">Proof of the Prime Number Theorem</h3>
<p>For the sake of time, we give up some elementary-ness for concision in the following proof of the Prime Number Theorem. In the spirit of analytic number theory as we tasted before with Euler&#39;s proof of the infinitude of primes, we will borrow some (in the grand scheme simple) tools from complex analysis, investigating the properties of some specific functions to get at the result we want. The original paper can be found <a href="https://people.mpim-bonn.mpg.de/zagier/files/doi/10.2307/2975232/fulltext.pdf">here</a>. If you aren&#39;t already familiar with holomorphic functions, types of convergence, complex integrals, and the like, here&#39;s a good time to catch up on it. Not much is totally needed, but we need to be careful of the details.</p>
<p>The ultimate idea of the proof is to analyze analytic properties of some functions to deduce results about their asymptotics.</p>
<p><strong>Prime Number Theorem:</strong> $\pi(x) \sim \frac{x}{\log(x)}$, that is, $\lim_{x \to \infty} \frac{\pi(x)}{x/\log(x)} = 1$.</p>
<p>From here on out, to simplify notation, $p$ will always refer to indexing primes, and as often as possible I&#39;ll try to keep $s \in \mathbb{C}$ reserved for complex variables and $x \in \mathbb{R}$ for real ones. The three functions of interest to us for this proof are:</p>
<ul>
<li>$\displaystyle \zeta(s) = \sum_{n=1}^{\infty} \frac{1}{n^s}$ (the Riemann Zeta Function)</li>
<li>$\displaystyle \vartheta(x) = \sum_{p \leq x} \log p$ (the first Chebyshev function)</li>
<li>$\displaystyle \Phi(s) = \sum_{p} \frac{\log p}{p^s}$ (I couldn&#39;t find a name for this one)</li>
</ul>
<p>The main goal of this proof is to prove the following equivalent statement.</p>
<p><strong>Theorem:</strong> The Prime Number Theorem is equivalent to $\vartheta(x) \sim x$.</p>
<p>This shouldn&#39;t be too surprising given that $π(x) = \sum_{p \leq x} 1$, so the logarithmic factor might be expected.</p>
<p><strong>Proof:</strong> We will appropriately bound the limits by each other to determine equality. First, note </p>
<center>

$\displaystyle \vartheta(x) = \sum_{p \leq x} \log p \leq \sum_{p \leq x} \log x = \pi(x) \log(x)$.

</center>

<!-- Dividing by $x$, and letting $x \rightarrow \infty$, -->
<p>Dividing by $x$,</p>
<center>

<!-- $\displaystyle \frac{\vartheta(x)}{x} \leq \frac{\pi(x) \log(x)}{x}$. -->
<!-- $\displaystyle \lim \limits_{x \rightarrow \infty} \frac{\vartheta(x)}{x} \leq \liminf\limits_{x\rightarrow \infty} \frac{\pi(x) \log(x)}{x}$ -->
$\displaystyle \frac{\vartheta(x)}{x} \leq \frac{\pi(x) \log(x)}{x}$

</center>

<!-- To get the corresponding lower bound, let $\alpha \in (0,1)$. -->
<p>To get the corresponding lower bound, let $\epsilon \in (0,1)$.</p>
<center>

<!-- $\displaystyle \vartheta(x) = \sum_{p \leq x} \log p \geq \sum_{x^\alpha \leq p \leq x} \log p \geq \left(\pi(x) - \pi(x^\alpha) \right) \log(x^\alpha) \geq \alpha \left(\pi(x) - x^\alpha \right)  \log(x)$ -->
$\begin{align} 

\vartheta(x) = \sum_{p \leq x} \log p \geq \sum_{x^{1-\epsilon} \leq p \leq x} \log p &amp; \geq \left(\pi(x) - \pi(x^{1-\epsilon}) \right) \log(x^{1-\epsilon}) \\ 
&amp; \geq (1-\epsilon) \left(\pi(x) - x^{1-\epsilon} \right)  \log(x)


\end{align}$


</center>

<!-- Again dividing by $x$ and letting $x \to \infty$: -->
<p>Again dividing by $x$,</p>
<center>

<!-- $\displaystyle 1 \geq \alpha \limsup\limits_{x\rightarrow \infty} \frac{\left(\pi(x) - x^\alpha \right) \log(x)}{x} = \alpha \limsup\limits_{x\rightarrow \infty} \frac{\pi(x) \log(x)}{x}$ -->
$\displaystyle \frac{\vartheta(x)}{x} \geq (1 - \epsilon) \frac{\left(\pi(x) - x^{1- \epsilon} \right) \log(x)}{x}$

</center>

<p>Combining everything,</p>
<center>

<!-- $\displaystyle 1 \leq \liminf\limits_{x\rightarrow \infty} \frac{\pi(x) \log(x)}{x} \leq \limsup\limits_{x\rightarrow \infty} \frac{\pi(x) \log(x)}{x} \leq \frac{1}{\alpha}$ -->
$\displaystyle (1 - \epsilon) \frac{\left(\pi(x) - x^{1- \epsilon} \right) \log(x)}{x} \leq \frac{\vartheta(x)}{x} \leq \frac{\pi(x) \log(x)}{x} $


</center>

<!-- Letting $\alpha \to 1^-$, we get $\lim\limits_{x\rightarrow \infty} \frac{\pi(x)}{x/\log x} = 1$. For the purposes of this proof, we do not need the other direction, so we leave it as is. $\blacksquare$ -->
<p>Since we can take $\epsilon \rightarrow 0$ and the term $x^{-\epsilon} \log(x) \rightarrow 0$ as $x \rightarrow \infty$, we get the sandwiched bounds (this can be explicitly written assuming either limit exists and taking limits and limit inferior/superior). $\blacksquare$</p>
<hr>
<p>We&#39;ll consider this equivalent statement with $\vartheta(x)$ since the &quot;jumps&quot; at each prime $p$ of $\log(p)$ instead of 1 as in $\pi(x)$ makes it slightly nicer to work with. We have already met the Riemann zeta function before and seen how it relates to primes directly with its product form. Let&#39;s now justify it a bit more concretely.</p>
<p><strong>Proposition (I):</strong> $\zeta(s)$ absolutely converges for $\Re(s)&gt;1$.</p>
<p><em>Proof:</em> $\displaystyle \sum_{n=1}^{\infty} \left| \frac{1}{n^s} \right| = \sum_{n=1}^{\infty} \left| \frac{1}{n^{\Re(s)}} \right| \left| \frac{1}{e^{i \Im(s) \log(n)}} \right| = \sum_{n=1}^{\infty} \frac{1}{n^{\Re(s)}}$. This converges since $\Re(s)&gt;1$. $\blacksquare$</p>
<p><strong>Corollary (Euler&#39;s Product Form):</strong> $\zeta(s) = \prod_{p}\left(1-p^{-s}\right)^{-1}$ for $\Re(s) &gt; 1$.</p>
<p><em>Proof:</em> We derived the above earlier assuming we could rearrange terms however we wanted, and absolute convergence gives us that prerequisite to do it safely (see <a href="https://en.wikipedia.org/wiki/Riemann_series_theorem">Riemann&#39;s rearrangment theorem</a>). $\blacksquare$</p>
<p><strong>Proposition (II):</strong> $\zeta(s) - \frac{1}{s-1}$ extends holomorphically to $\Re(s)&gt;0$.</p>
<p><em>Proof:</em> The idea of looking at this function is to note that the right term $\frac{1}{s-1}$ is the integral of the infinite sum that defines $\zeta(s)$. While neither may be defined for $\Re(s) &gt; 0$ individually, their difference will cancel out just right to give us the extension we want. If this isn&#39;t clear, think about how the harmonic series and its related integral both diverge, but their difference gives rise to the <a href="https://en.wikipedia.org/wiki/Euler%27s_constant">Euler-Mascheroni Constant</a>. So, with this in mind, we use a clever rewriting of this difference, and bound it appropriately to show it converges uniformly (on compact sets) via the Weierstrass M-test, hence showing such a limiting function exists and by uniform convergence is also holomorphic. First, note</p>
<center>

$\displaystyle \zeta(s) - \frac{1}{s-1} = \sum_{n=1}^{\infty} \frac{1}{n^s} - \int_1^\infty \frac{1}{x^s} \mathrm{d}x = \sum_{n=1}^{\infty} \int_n^{n+1} \left( \frac{1}{n^s} - \frac{1}{x^s} \right) \mathrm{d}x$

</center>

<p>with the Fundamental Theorem of Calculus, we can further rewrite the integral terms: </p>
<center>

$\displaystyle \int_n^{n+1} \left( \frac{1}{n^s} - \frac{1}{x^s} \right) \mathrm{d}x = \int_n^{n+1} \left( \int_{x}^{n} \frac{\mathrm{d}}{\mathrm{d}u}\left( \frac{1}{u^s} \right) \mathrm{d}u \right) \mathrm{d}x = \int_n^{n+1}  \int_{x}^{n} \frac{-s}{u^{s+1}} \mathrm{d}u \ \mathrm{d}x$

</center>

<p>Now let&#39;s see if we can bound this to apply the M-test:</p>
<center>

$\displaystyle \left| \int_n^{n+1}  \int_{x}^{n} \frac{-s}{u^{s+1}} \mathrm{d}u \ \mathrm{d}x \right| \leq  \frac{1}{2} \max_{n \leq u \leq n+1} \left| \frac{s}{u^{s+1}} \right| \leq \frac{\left| s \right|}{n^{\Re(s)+1}} \leq \frac{C}{n^{\delta+1}} := M_n$

</center>

<p>We evaluate the modulus as we did before, and the maximum is given since the fraction is decreasing in $u$. Now for any compact i.e. closed and bounded set $K \subseteq \{ s \in \mathbb{C} \ : \ \Re(s) &gt; 0 \}$, since $|s|$ and $\Re(s)$ are continuous, they achieve their bounds so there are constants $C = \max \{ |s| \ : \ s \in K \}$ and $\delta = \min \{ \Re(s) \ : \ s \in K \}$. Since $\delta &gt; 0$, the sum of $M_n$ converge and so by the M-test get that our sum defining the function converges uniformly and absolutely giving us existence of such a function. Since it also converges uniformly on compacts in the region $\Re(s)&gt;0$ and the finite sums $f_k(s) = \sum_{n=1}^{k} \int_n^{n+1} \left( \frac{1}{n^s} - \frac{1}{x^s} \right) \mathrm{d}x$ are holomorphic, the limit $\zeta(s) - \frac{1}{s-1}$ is holomorphic as well. $\blacksquare$</p>
<p><strong>Proposition (III):</strong> $\vartheta(x) = O(x)$ i.e. there are constants $C,x_0$ such that for all $x\geq x_0$, we have  $\left| \vartheta(x) \right| \leq C \left| x \right| $.</p>
<p><em>Proof:</em> Using similar methods from before,</p>
<center>

$\displaystyle 2^{2n} = (1+1)^{2n} = \sum_{k=0}^{2n} {2n \choose k} \geq {2n \choose n} \geq \prod_{n \leq p \leq 2n} p = e^{\sum_{n \leq p \leq 2n} \log p} = e^{\vartheta(2n) - \vartheta(n)}$

</center>

<p>Hence $\vartheta(2n) - \vartheta(n) \leq 2n \log(2)$. We can now extend this to all $x$ instead of just even $x = 2n$ also in a similar method from before. Let $n = \lfloor x/2 \rfloor$:</p>
<center>

$\begin{align}

\vartheta(x) - \vartheta(x/2) &amp; =  \big( \vartheta(x) - \vartheta(2n) \big) + \big( \vartheta(2n) - \vartheta(n) \big) + \big( \vartheta(n) - \vartheta(x/2) \big) \\
&amp; \leq \sum_{2n &lt; p \leq x} \log p + 2n\log(2) - \sum_{n \leq p \leq x/2} \log p \\
&amp; \leq 2 \log(x) + 2n\log(2) \\
&amp; \leq 2x + x\log(2)\\
&amp; \leq (2+\log(2))x


\end{align}$

</center>

<p>The first few inequalties are just writing out the sums and checking indices correctly. We obtain the second-to-last inequality by noting by choice $2n \leq x$ and $\log(x) \leq x$. Let $C = 2+\log(2)$. Now let $r$ be the least integer such that $1&gt;x/2^r$.</p>
<center>

$\begin{align}

\vartheta(x) &amp; = \left(\vartheta(x) - \vartheta(x/2) \right) + \cdots + \left(\vartheta(x/2^{r-1}) - \vartheta(x/2^{r}) \right) + \vartheta(x/2^{r}) \\
&amp; \leq Cx + C(x/2) + \cdots C(x/2^{r-1}) + 0 \\
&amp; \leq 2Cx

\end{align}$

</center>

<p>This works for all $x&gt;1$, hence showing $\vartheta(x) = O(x)$. (Note: this bound is quite bad, but we used it to get concrete values to see clearly $\vartheta(x) = O(x) $. In particular, if you use the fact that $\log(x) = o(x)$, you can make $C$ as close to $\log(2)$ as you want for sufficiently large $x \geq x_0$, and this is what the original proof does) $\blacksquare$</p>
<p><strong>Proposition (IV):</strong> For $\Re(s)\geq 1$, $\zeta(s) \neq 0$ and $\Phi(s) - \frac{1}{s-1}$ is holomorphic.</p>
<!-- https://rtullydo.github.io/complex-analysis-411-notes/section-14.html -->
<p><em>Proof:</em> By <strong>Proposition (I)</strong> and the Euler Product Form, we can show $\zeta(s) \neq 0$. It might seem intuitively obvious that $\zeta(s) \neq 0$ since $1-p^{-s} \neq 0$ and so we are taking the product of non-zero terms, but since our product is infinite, we have to check that the product doesn&#39;t shrink too fast. For example, even though $\frac{n}{n+1} \neq 0$, the product</p>
<center>

$\displaystyle \prod_{n=1}^\infty \frac{n}{n+1} = \lim_{n\to\infty} \frac{1}{n+1} = 0$

</center>

<p>Note that $\left(1-p^{-s} \right)^{-1} - 1 = \left( p^s - 1 \right)^{-1}$ is absolutely convergent for $\Re(s) &gt; 1$ since $\left| \left( p^s - 1 \right)^{-1} \right| = \left| p^{-s} / \left( 1 - p^{-s} \right) \right| =  p^{-\Re(s)} / \left| 1 - p^{-s} \right| \leq p^{-\Re(s)}/2$. So in particular, this means that $\left(1-p^{-s} \right)^{-1} \rightarrow 1$ as we run through increasing primes. Let $N$ be the integer such that $\left(1-p^{-s} \right)^{-1} \in B(1,1/2)$ for $p \geq N$, so we can write the product</p>
<!-- $\left| \left( p^s - 1 \right)^{-1} \right| \leq \left| \left( p^{\Re(s)} - 1 \right)^{-1} \right| \leq p^{-\Re(s)}$. -->
<center>

$\displaystyle \prod_p \frac{1}{1-p^{-s}} = \prod_{2\leq p &lt; N} \frac{1}{1-p^{-s}} \ \cdot \ \prod_{N \leq p} \frac{1}{1-p^{-s}}$

</center>

<p>Since the second product&#39;s terms are bounded away from 0, we can use the (standard branch of the) complex logarithm $\log(z) = \ln(|z|) + i\arg(z)$.</p>
<center>

$\displaystyle \log \left( \prod_{N \leq p} \frac{1}{1-p^{-s}} \right) = \sum_{N \leq p} \log\left( \frac{1}{1-p^{-s}} \right) \leq \sum_{N \leq p} 2 \left| \frac{1}{1-p^{-s}}  - 1 \right|$

</center>

<p>getting the last inequality via the Taylor series for $\log(z+1)$. We showed above this last sum converges, so the $\log$ sum converges, and in particular by the continuity of $e^x$ the product converges:</p>
<center>

$\displaystyle \prod_{N \leq p} \frac{1}{1-p^{-s}} = \exp \left( \sum_{N \leq p} \log\left( \frac{1}{1-p^{-s}} \right) \right) \neq 0$.

</center>

<p>Since the individual terms $\frac{1}{1-p^{-s}}$ are non-zero, we get on the whole that for $\Re(s) &gt; 1$,</p>
<center>

$\displaystyle \zeta(s) = \prod_p \frac{1}{1-p^{-s}} \neq 0$

</center>

<p>To start on the second part, we build off a bit of what we just talked about noting that $\log(\zeta(s)) = -\sum_p \log\left(1-p^{-s} \right)$. Differentiating,</p>
<!-- -\sum_p \frac{\mathrm{d}}{\mathrm{d}s}\log\left( 1-p^{-s} \right) -->
<center>

$\displaystyle -\frac{\zeta&#39;(s)}{\zeta(s)} = \sum_p \frac{p^{-s}\log(p)}{1-p^{-s} } = \sum_p \frac{\log(p)}{p^{s} - 1 } = \Phi(s) + \sum_p \frac{\log(p)}{p^s \left( p^{s} - 1 \right) }$

</center>

<p>So in particular,</p>
<center>

$\displaystyle \Phi(s) = -\frac{\zeta&#39;(s)}{\zeta(s)} - \sum_p \frac{\log(p)}{p^s \left( p^{s} - 1 \right) }$

</center>


<p>The sum on the right converges for $\Re(s) &gt; \frac{1}{2}$. So the only possibilities for problematic poles for $\Phi(s)$ come from the term $-\zeta&#39;(s)/\zeta(s)$. By <strong>Proposition (II)</strong>, we can extend $\zeta(s)$ to a meromorphic function on $\Re(s)&gt;0$ with a simple pole at $s=1$. Thus, $-\zeta&#39;(s)/\zeta(s)$ has simple poles at $s=1$ and the zeroes of $\zeta(s)$. We already showed $\zeta(s) \neq 0$ for $\Re(s) &gt; 1$, so if we want to show there are no problems for $\Phi(s)$, we just need to show that there are no zeroes for $\zeta(s)$ on $\Re(s)=1$. We will do so by contradiction by considering multiple zeroes on the line $\Re(s)=1$.</p>
<!-- All together, we can extend $\Phi(s)$ meromorphically to $\Re(s)>\frac{1}{2}$ with the same simple poles as $-\zeta'(s)/\zeta(s)$. -->
<p>Suppose that $\zeta(s)$ has a zero of order $\mu$ at $s=1+i\alpha$ and a zero of order $\nu$ at $s=1+2i\alpha$ for $\alpha \in \mathbb{R} \setminus \{ 0 \}$. Since $\Phi$ has a simple pole at $s=1$, it has associated residue $1$ (note the sign is flipped since we have $-\zeta&#39;(s)/\zeta(s)$ instead of $\zeta&#39;(s)/\zeta(s)$), and for a zero of $\zeta(s)$ of order $k$ it also has residue $-k$.</p>
<center>

$\displaystyle \lim_{\epsilon \to 0^+} \epsilon \Phi(1+\epsilon) = 1, \ \lim_{\epsilon \to 0^+} \epsilon \Phi(1+\epsilon \pm i\alpha) = -\mu, \ \lim_{\epsilon \to 0^+} \epsilon \Phi(1+\epsilon \pm 2i\alpha) = -\nu$

</center>

<p>We include both zeroes $1 \pm i\alpha$ since $\zeta(\bar{s}) = \overline{\zeta(s)}$. Now, consider the sum</p>
<!-- <center>

$\displaystyle \zeta(\bar{s}) = \sum_{n} \frac{1}{n^{\bar{s}}} = \sum_{n} \frac{1}{n^{\Re(s)} \cdot e^{-\Im(s) \log n}}  = \overline{\sum_{n} \frac{1}{n^{\Re(s)} \cdot e^{\Im(s) \log n}}} = \overline(\zeta(s))$

</center> -->
<center>

$\displaystyle \sum_{r=-2}^2 {4 \choose 2+r} \Phi(1+\epsilon+ri\alpha) = \sum_p \frac{\log p}{p^{1+\epsilon}}\left( p^{i\alpha/2} + p^{-i\alpha/2} \right)^4 \geq 0$

</center>

<p>The first equality is by direct computation, and we get the inequality since sums of conjugates are real and hence their 4th powers are non-negative real numbers. Now mulitplying through by $\epsilon&gt;0$ and taking the limit $\epsilon \to 0$:</p>
<center>

$\displaystyle 0 \leq \lim_{\epsilon \to 0} \sum_{r=-2}^2 {4 \choose 2+r} \epsilon \Phi(1+\epsilon+ri\alpha) = 6 - 2\nu - 8\mu$

</center>

<p>Since the only pole of $\zeta(s)$ for $\Re(s)&gt;0$ is at $s=1$, $1+\epsilon+ri\alpha$ must be zeroes of positive order i.e. $\mu, \nu \geq 0$. Therefore, $2\nu + 8\mu \leq 6$ can only hold if $\mu=0$ i.e. $\zeta(1+i\alpha) \neq 0$. </p>
<p>Hence $\Phi(s)$ only has the simple pole at $s=1$ for $\Re(s) \geq 1$, and hence $\Phi(s) - \frac{1}{s-1}$ is holomorphic on that half-plane. $\blacksquare$</p>
<p>Next we strengthen our result from <strong>(III)</strong> to show that $\vartheta(x) \sim x$. </p>
<p><strong>Proposition (V):</strong> $\displaystyle \int_1^\infty \frac{\vartheta(x) - x}{x^2} \ \mathrm{d}x$ is a convergent integral.</p>
<p>The idea is that if $\vartheta(x) \approx \lambda x$ for $\lambda &gt; 1$, then the integral would be approximately $\int_1^\infty \frac{\lambda x - x}{x^2} \ \mathrm{d}x = \int_1^\infty (\lambda-1) \frac{1}{x} \ \mathrm{d}x$, which 
would diverge; the convergence of the integral forces the integrand to decay at the rate we want. We will do this with what Newman calls the <em>Analytic Theorem</em>.</p>
<p><strong>Analytic Theorem.</strong> Let $f(t)$ $(t \geq 0)$ be a bounded and locally integrable function and suppose that the function $g(z) = \int_0^{\infty} f(t) e^{-zt} \ \mathrm{d}t$ $(\Re(z) &gt; 0)$ extends holomorphically to $\Re(z) \geq 0$. Then $\int_0^{\infty} f(t) \ \mathrm{d}t$ exists (and equals $g(0)$).</p>
<p>The idea of this theorem is to take the Laplace transform of $f(t)$ analyze its &quot;spectrum&quot;. If the spectrum analysis is nice and differentiable, it means that around $s=0$, $g$ can&#39;t have singularities that blow up and so make the integral of $f$ blow up; the behavior of $g$ limits the behavior of $f$. I&#39;ll leave the proof of the theorem to the original paper, but the idea above is enough (especially if you have seen the Laplace transform before).</p>
<p><em>Proof of V:</em> The function $\Phi(s)$ looks a lot like $\vartheta(x)$. For $\Re(s)&gt;1$, we can interchange the sum in $\Phi(s)$ with an integral:</p>
<center>

<!-- $\displaystyle \Phi(s) = \sum_p \frac{\log p}{p^s} = \int_1^\infty \frac{\mathrm{d}\vartheta(x)}{x^s} = s \int_{1}^{\infty} \frac{\vartheta(x)}{x^{s+1}} \ \mathrm{d}x = s \int_{0}^{\infty} e^{-st}\vartheta(e^t) \ \mathrm{d}t$  -->
$\displaystyle \Phi(s) = \sum_p \frac{\log p}{p^s} = \int_1^\infty \frac{1}{x^s} \ \mathrm{d}\vartheta(x)$ 

</center>

<p>Note the differential is with respect to $\mathrm{d}\vartheta(x)$ as opposed to just $\mathrm{d}x$. If you aren&#39;t familiar with measure theory and the Lebesgue integral, the idea is that we are &quot;stretching&quot; the x-axis according to $\vartheta(x)$, giving weights to the intervals we&#39;re integrating over with respect to $\vartheta(x)$. If $g(x)$ was differentiable, it might be more familiar to write this transformed interval as $\mathrm{d}g(x) = g&#39;(x) \ \mathrm{d}x$. <a href="https://en.wikipedia.org/wiki/Riemann%E2%80%93Stieltjes_integral">Here are more details on the specific case we&#39;re working with</a>. We get the sum equivalence since $\vartheta(x)$ is a step function, so we only evaluate at the step discontinuities at the primes. Most usefully for us, these types of integrals admit a type of integration by parts. </p>
<!-- In particular, $\mathrm{d} \vartheta(x)$ means take integral with measure $\mu_{\vartheta}(E) = \sum_{p \in E} \log p$ -->
<center>

<!-- $\displaystyle \Phi(s) = \sum_p \frac{\log p}{p^s} = \int_1^\infty \frac{\mathrm{d}\vartheta(x)}{x^s} = s \int_{1}^{\infty} \frac{\vartheta(x)}{x^{s+1}} \ \mathrm{d}x = s \int_{0}^{\infty} e^{-st}\vartheta(e^t) \ \mathrm{d}t$  -->
$\begin{align} 

\int_1^\infty \frac{1}{x^s} \ \mathrm{d}\vartheta(x) &amp; = \left[ \frac{1}{x^s} \cdot \vartheta(x) \right]_{1}^{\infty} - \int_1^\infty \vartheta(x) \ \mathrm{d} \left( \frac{1}{x^s} \right) \\
&amp; = \left[ \frac{1}{x^s} \cdot \vartheta(x) \right]_{1}^{\infty} - \int_1^\infty \vartheta(x) \frac{-s}{x^{s+1}} \ \mathrm{d}x \\
&amp; = 0 + s \int_1^\infty \frac{\vartheta(x)}{x^{s+1}} \ \mathrm{d}x \\
&amp; = s \int_0^\infty \frac{\vartheta(e^t)}{e^{ts}} \ \mathrm{d}t

\end{align}$

</center>

<p>Note since $\vartheta(x) = O(x)$ and $\Re(s)&gt;1$, we have $\left| \vartheta(x)/x^s \right| \leq C/x^{\Re(s)-1} \rightarrow 0$ as $x\to\infty$. With the exact same bounding, we see the integral term is also convergent. We get the last equality substituting $x=e^t$. Now we apply the Analytic Theorem to $f(t) = \vartheta(e^t)e^{-t} - 1$ and $g(z) = \Phi(z+1)/(z+1) - 1/z$. To verify, note that from the above derivation we have</p>
<center>

$\begin{align} 

\frac{\Phi(z+1)}{z+1} &amp; = \int_0^\infty \vartheta(e^t)e^{-t(z+1)} \ \mathrm{d}t \\
&amp; = \int_0^\infty \vartheta(e^t)e^{-t}e^{-zt} \ \mathrm{d}t \\
&amp; = \int_0^\infty \left(f(t) + 1 \right)e^{-zt} \ \mathrm{d}t \\
&amp; = \int_0^\infty f(t) e^{-zt} \ \mathrm{d}t + \frac{1}{z} \\

\end{align}$

</center>

<p>Note by <strong>(III)</strong>, $\vartheta(e^t) = O(e^t)$, so $f(t) = \vartheta(e^t)e^{-t} - 1 = O(1)$ and so is bounded, and only has countably many discontinuities at $\log p$ for primes $p$ where $\vartheta(x)$ has its jump discontinuities at the primes and thus is locally integrable (i.e. integrable on every closed subinterval of $(0,\infty)$). By <strong>(IV)</strong>, $g(z) = \frac{\Phi(z+1)}{z+1} - \frac{1}{z} = \frac{\Phi(z+1) - 1/z - 1}{z+1}$ extends holomorphically to $\Re(z) \geq 0$ since $z+1 \neq 0$ and $\Phi(z+1) - 1/z$ is holomorphic for $\Re(z) \geq 0$. So we use the <strong>Analaytic Theorem</strong> and conclude that </p>
<center>

$\displaystyle g(0) = \int_0^\infty f(t) \ \mathrm{d}t = \int_0^\infty \vartheta(e^t)e^{-t} - 1 \ \mathrm{d}t = \int_0^\infty \frac{\vartheta(x) - x}{x^2} \ \mathrm{d}x$

</center>

<p>is a convergent integral. $\blacksquare$</p>
<p><strong>Prime Number Theorem:</strong> $\vartheta(x) \sim x$.</p>
<p><em>Proof:</em> For contradiction, assume that $\lim\limits_{x \to \infty} \vartheta(x)/x \neq 1$. We check two cases. First, say for some $\lambda &gt; 1$, $\limsup\limits_{x\rightarrow \infty} \vartheta(x)/x \geq \lambda$ i.e. there are arbitrarily large $x_n$ such that $\vartheta(x_n) \geq \lambda x_n$ (we drift too far above $x$). Also, since $\vartheta(x)$ is non-decreasing, we have $\min\limits_{t \in [x_n, \lambda x_n]} \vartheta(t) = \vartheta(x_n) \geq \lambda x_n$. Hence integrating over this interval,</p>
<!-- For contradiction, assume that $\limits_{x\limsup\rightarrow \infty} \vartheta(x)/x \geq 1$. -->
<center>

$\displaystyle \int_{x_n}^{\lambda x_n} \frac{\vartheta(t) - t}{t^2} \ \mathrm{d}t \geq \int_{x_n}^{\lambda x_n} \frac{\lambda x_n - t}{t^2} \ \mathrm{d}t = \int_1^{\lambda} \frac{\lambda - t}{t^2} \ \mathrm{d}t = \lambda - 1 - \log \lambda &gt; 0$

</center>

<p>Picking the $x_n$ such that the intervals $[x_n, \lambda x_n]$ are disjoint, we get</p>
<center>

$\displaystyle \int_1^\infty \frac{\vartheta(t) - t}{t^2} \ \mathrm{d}t \geq \sum_{n=0}^\infty \int_{x_n}^{\lambda x_n} \frac{\vartheta(t) - t}{t^2} \ \mathrm{d}t \geq \sum_{n=0}^\infty \lambda - 1 - \log \lambda = \infty$

</center>

<p>This contradicts the convergence established in <strong>(V)</strong>, and so $\limsup\limits_{x\rightarrow \infty} \vartheta(x)/x \leq 1$. Similarly, if we assume $\liminf\limits_{x\rightarrow \infty} \vartheta(x)/x \leq \lambda &lt; 1$, i.e. there are abitrarily large $x_n$ such that $\vartheta(x_n) \leq \lambda x_n$, we get a similar divergence looking at the interval $[\lambda x_n, x_n]$. </p>
<center>

$\displaystyle \int_{\lambda x_n}^{x_n} \frac{\vartheta(t) - t}{t^2} \ \mathrm{d}t \leq \int_{\lambda x_n}^{x_n} \frac{\lambda x_n - t}{t^2} \ \mathrm{d}t = \int_\lambda^{1} \frac{\lambda - t}{t^2} \ \mathrm{d}t =\log\lambda - (\lambda - 1) &lt; 0$

</center>

<p>Therefore $1 \leq \liminf\limits_{x\rightarrow \infty} \vartheta(x)/x \leq \limsup\limits_{x\rightarrow \infty} \vartheta(x)/x \leq 1$ and so $\lim\limits_{x\to\infty} \vartheta(x)/x=1$. $\blacksquare$</p>
<hr>
<p>Thus, we have proven one of the most fundamental results in analytic number theory.</p>
<h3 id="do-we-need-the-primes-at-all-">Do We Need the Primes At All?</h3>
<p>I want to note not much of this proof actually used any key properties of the primes. The only time we ever actually used &quot;primeness&quot; was in deducing the Euler product form to show that $\zeta(s) \neq 0$ for $\Re(s) \geq 1$. The rest followed from analytic properties of the functions $\pi(x)$, $\Phi(s)$, and $\vartheta(x)$. If you can find another subset of $\mathbb{N}$ that implied similar non-vanishing properties, this proof could be easily adapted. For instance, for any subset $S \subseteq \mathbb{N}$, we can let $\pi_S(x) = \left| S \cap \mathbb{N}_{\leq x} \right| = \# \{ n \leq x \ : \ n \in S \}$ i.e. $\pi_S(x)$ is the $S$ counting function instead of prime counting function. Similarly let $\vartheta_S(x) = \sum_{s \in S, s \leq x} \log s$, we have the equivalence from before with the same proof.</p>
<p><strong>Theorem:</strong> $\pi_S(x) \sim \frac{x}{\log x}$ if and only if $\vartheta_S(x) \sim x$.</p>
<p>What was hard was establishing either of these asymptotics, which is where the analytic properties became important, and in particular needed the primes and fundamental theorem of arithmetic to establish the non-vanishing of $\zeta(s)$.</p>
<h2 id="consequences-of-the-prime-number-theorem">Consequences of the Prime Number Theorem</h2>
<p>The Prime Number Theorem allows us to extend and strengthen many of the results we have already spent time combing through. Quite possibly the most immediate allows us to estimate the number of primes less than or equal to $n$.</p>
<p><strong>Corollary:</strong> $\displaystyle \pi(n) \approx \frac{n}{\log n}$.</p>
<p>Of course, this is only useful for large $n$ as we approach the asymptotics. The actual estimate given by $n/\log n$ isn&#39;t great, and often in practice it is better to use the <strong>Logarithmic integral</strong>.</p>
<p><strong>Proposition:</strong> The PNT is equivalent to $\pi(x) \sim \mathrm{Li}(x) = \int_2^x \frac{\mathrm{d}t}{\log t}$.</p>
<p><strong>Proof:</strong> This follows from the fact that $\mathrm{Li}(x) \sim \frac{x}{\log x}$ as well, and that can be obtained with integration by parts. <a href="https://willhoffer.com/2021-11-14/asymptotics-of-the-logarithmic-integral/">If interested, you can read the whole induction to obtain the asymptotics here</a>. $\blacksquare$</p>
<!-- f(x)~g(x) and h(x)~g(x), then f(x)~h(x) -->
<p>This roughly makes sense to be a better estimate of $\pi(n)$, as it is a more &quot;dynamic&quot; estimate by integrating over the &quot;density&quot; of the primes suggested by the PNT. For a small interval $(t, t + \epsilon]$ around $t$, the number of primes in that interval is approximately </p>
<center>

$\displaystyle \mathrm{d \pi} \approx \frac{\mathrm{d}}{\mathrm{d}t} \left( \frac{t}{\log t} \right) \ \mathrm{d}t = \frac{\log t - 1}{(\log t)^2} \ \mathrm{d}t \approx \frac{\mathrm{d}t}{\log t}$

</center>

<p>More crudely, just consider $\pi(t+dt) - \pi(t) = \frac{t+dt}{\log(t+dt)} - \frac{t}{\log t} \approx \frac{t+dt}{\log t} - \frac{t}{\log t} \approx \frac{dt}{\log t}$. The point is that this integral uses the estimate of the PNT to create tighter bounds in accordance to how far along we have counted, as opposed to uniformly treating the number of primes in an interval the same everywhere. <a href="https://arxiv.org/pdf/1311.1093">You can read more on this specific estimate here</a>.</p>
<p>This estimate should hopefully look familiar, as it and the Prime Number Theorem affirm one of our big suspicians originally! Remember we found heuristically, by considering the Sieve of Eratosthenes, that the probability of $n$ being prime should be about the probability of $n$ not being divisible by any number $x&lt;n$ which resulted in a probability of $1/\log n$. The derivative should make this even more concrete, and even more simply, the number of primes less than $n$ is $\pi(n)$, so the probability of a number up to $n$ being prime should be about $\pi(n)/n \approx 1/\log n$. This also then gives the interpretation that the average gap between primes less than or equal to $n$ is about $\log n$.</p>
<p>So, if you need a prime, let&#39;s say around $2^{512}$ for cryptographic purposes, the odds of a number around there being prime is about $1/\log(2^{512}) \approx 1/356$. Since even numbers are obviously not prime, we need to check on average about $356/2 = 178$ numbers to find a prime of that magnitude (and this is without any optimizations, or fault tolerances in allowing probable primes like before).</p>
<!-- Mauerer's probable prime generating algorithm: https://link.springer.com/article/10.1007/BF00202269 -->
<h3 id="estimating-the-nth-prime-number">Estimating the nth Prime Number</h3>
<p>The Prime Number Theorem implies a similar type of inverse relation. As before, let $p_n$ be the $n^\textrm{th}$ prime number.</p>
<p><strong>Proposition:</strong> $p_n \sim n \log n$.</p>
<p><em>Proof:</em> This follows since $n = \pi(p_n) \sim \frac{p_n}{\log p_n}$ i.e. $p_n \sim n \log p_n$. This is almost what we want, so resubstituting the relation back into itself one more time gives </p>
<center>

$\displaystyle p_n \sim n \log p_n \sim n \log (n \log p_n) \sim n\log n + n\log \log p_n \sim n \log n$

</center>

<p>This works in particular because logarithms preserve asymptotics for functions increasing to $\infty$, and the PNT implies $\log p_n \sim \log n$. So we can rewrite these substitutions of $p_n$ as substitutions of $\log p_n$. $\blacksquare$</p>
<!-- From f/g = 1, then log(f)/log(g) = [log(g) + log(f/g)]/log (g) = 1 + log(f/g)/log(g) = 1 + 0/infty = 1 -->
<!-- Using similar logic and taking logarithms of the actual limit statement of the PNT can add more rigor to the above if wanted. $\blacksquare$  -->
<!-- https://www.quora.com/How-does-the-Prime-Number-Theorem-imply-that-the-nth-prime-number-is-very-close-to-n-log-n-as-n-grows-very-large -->
<!-- https://proofwiki.org/wiki/Approximate_Value_of_Nth_Prime_Number -->
<p>We saw before a few attempts to find prime generating formulae, and while the PNT doesn&#39;t give us one directly, it gives us a method to at least <em>estimate</em> the nth prime. Like the original Prime Number Theorem estimate, this isn&#39;t that great of an approximation. Since $n = \pi(p_n) \sim \mathrm{Li(p_n)}$, we get the better approximation that $p_n \sim \mathrm{Li}^{-1}(n)$ (note this works due to monotonicity). A better second order estimation given by analyzing the Logarithmic integral is </p>
<center>

$\displaystyle p_n \sim n\log n + n\log \log n - n$

</center>

<p>It seems we get close to something like this directly from our asymptotics above, but we need more careful analysis to get here. Cipolla found this originally in 1902 (of reference I cannot find), but there have been more elaborate methods that result from looking at $\mathrm{Li}^{-1}$. One such developed for more general inversion problems can be found <a href="https://inria.hal.science/inria-00076983/document">here (helpfully, also in English)</a>. Here is one possible, more numeric idea to get this better approximation. We start with the better estimate of $n = \pi(p_n) = \mathrm{Li}(p_n)$. By using the asymptotic expansion given by the integration by parts, we obtain the better estimate</p>
<center>

$\displaystyle \mathrm{Li}(x) \sim \frac{x}{\log x} \sum_{n=0}^\infty \frac{n!}{\left(\log x \right)^n} \sim \frac{x}{\log x} \sum_{n=0}^\infty \frac{1}{\left(\log x \right)^n} = \frac{x}{\log x} \cdot \frac{1}{1 - \frac{1}{\log x}} = \frac{x}{\log x - 1}$

</center>

<p>Again using $\pi(p_n) = n$, we get</p>
<center>

<!-- $\displaystyle n \sim \frac{p_n}{\log p_n - 1}$ -->
$\displaystyle p_n \sim n \left( \log p_n  - 1 \right) = f(p_n)$

</center>

<p>Hence, we want to approximate solutions to $f(x) = x$. Now, note that $f&#39;(x) = \frac{n}{x} &lt; 1$ since $p_n &gt; n$. Hence, by the Contraction Mapping Theorem, this equation has a (stable) fixed point which we know to be $p_n$, so we can iteratively give guesses to get better and better approximations of the fixed point $p_n$. We start with our initial guess we got before of $p_n \approx n \log n$.</p>
<center>

$\displaystyle p_n \approx n \left( \log \left( n \log n \right)  - 1 \right) = n \left( \log n + \log \log n   - 1 \right) = n \log n + n \log \log n - n$

</center>

<p>which was the better estimate from before! We can plug this in again to get one more estimate, but since we are adding terms together, it won&#39;t simplify as cleanly.</p>
<center>

$\displaystyle p_n \approx n \log \left( n \log n + n \log \log n - n \right) - n$

</center>

<p>Heuristically, though, this approximation performs worse, likely due to the accumulated errors ignored in our estimations and asymptotics; what we really want to solve is $\pi(p_n) = n$, but we can only estimate $\pi(n)$. This results in a fixed point solution that may be close to $p_n$, but not exactly.</p>
<!-- One way to understand this is through the [relative condition number](https://en.wikipedia.org/wiki/Condition_number#One_variable) that quantifies the relative sensitivity of our solutions (the nth prime number $p_n$) to small changes and errors in the input ($n$). Since we are effectively solving $p_n = \pi^{-1}(n)$, we get that

<center>

$\displaystyle \left| \frac{n \cdot \left(\pi^{-1} \right)'(n)}{\pi^{-1}(n)} \right| = \left| \frac{n \cdot \frac{1}{\pi' \left( \pi^{-1}(n) \right)}}{\pi^{-1}(n)}  \right| = \left| \frac{n \cdot \frac{1}{\frac{1}{\log \left( \pi^{-1}(n) \right)}}}{\pi^{-1}(n)}  \right| = \left| \frac{n \log p_n}{p_n}  \right| $

</center> -->
<h3 id="revisiting-bertrand-s-postulate">Revisiting Bertrand&#39;s Postulate</h3>
<p>The Prime Number Theorem allows us to strengthen and show some of the results we have already discussed. For instance, Bertrand&#39;s postulate falls out almost immediately from the estimates given by the PNT.</p>
<center>

$\displaystyle \pi(2n) - \pi(n) \sim \frac{2n}{\log(2n)} - \frac{n}{\log n} \sim \frac{n}{\log n}$

</center>

<p>So for large $n$, there is not only at least one prime, but many primes in the interval $(n, 2n]$. Of course, our original proof of Bertrand&#39;s Postulate has its benefits, one being that its concrete and establishes at least one prime for <em>all</em> intervals like this, rather than the slightly more vague asymptotic notion. Perhaps a bit more interestingly is that this shows that there are roughly the same number of primes in the interval $(0,n]$ as there is from $(n,2n]$, which is a bit surprising given that $\pi(n)$ isn&#39;t linear. But because $\log n$ grows slow enough, the asymptotics balance out. Similarly, we can strengthen Bertrand&#39;s Postulate to any non-zero interval $(n, (1+\epsilon)n]$.</p>
<center>

$\displaystyle \pi((1+\epsilon)n) - \pi(n) \sim \frac{(1+\epsilon)n}{\log((1+\epsilon)n)} - \frac{n}{\log n} \sim \frac{\epsilon n}{\log n}$

</center>

<p>So all we need is $n$ to be large enough to overcome the scaling of $\epsilon$; we can take a &quot;small&quot; enough interval given that $n$ is big enough to make that interval have enough room for primes to occur. How big that $n$ must be is not super easy to get given that we haven&#39;t done any of the (also difficult) error analysis of the Prime Number Theorem, but a good estimate might just start with getting this asymptotic term greater than 1.</p>
<h3 id="a-quick-application-of-the-prime-number-theorem">A Quick Application of the Prime Number Theorem</h3>
<p>To round things off, here&#39;s a quick application of the PNT. While it is nonetheless an interesting and key result about the behavior and distribution of primes, the PNT is not just a novelty and can be used to give bounds on other prime related problems. In particular because it tells us that the average gap of primes around $n$ is $\log n$, they occur just frequently enough for their harmonic style sum to grow logarithmically slower than the typical harmonic sum, and so still diverge.</p>
<p><strong>Proposition:</strong> $\sum_{p \textrm{ prime}} \frac{1}{p}$ diverges.</p>
<p><strong>Proof:</strong> We can use a Riemann-Stieltjes style integral rewriting like we did before, and use integration by parts.</p>
<center>

$\displaystyle \sum_{p \leq t} \frac{1}{p} = \int_{2}^{t} \frac{1}{x} \ \mathrm{d}\pi(x) = \left[ \frac{\pi(x)}{x} \right]_2^t - \int_2^t \frac{-\pi(x)}{x^2} \ \mathrm{d}x = \frac{\pi(t)}{t} - \frac{\pi(2)}{2} + \int_2^t \frac{\pi(x)}{x^2} \ \mathrm{d}x$

</center>

<p>Applying the PNT, we get</p>
<center>

$\displaystyle \sum_{p \leq t} \frac{1}{p} \sim \frac{1}{\log t} + \int_2^t \frac{1}{x \log x} \ \mathrm{d}x \sim \frac{1}{\log t} + \log\log t - \log \log 2$

</center>

<p>$\log \log t \to \infty$ as $t \to \infty$, hence the sum $\sum_p \frac{1}{p}$ diverges. $\blacksquare$</p>
<p>Alternatively, <a href="https://youtu.be/u3po6EyQKn4?si=Wp5rVYB8LsA9Cc5_">here&#39;s a direct proof of the above result that avoids using the PNT</a>.</p>
<h2 id="an-analogue-to-the-prime-number-theorem-in-k-x-">An Analogue to the Prime Number Theorem in $K[x]$</h2>
<p>Before finshing this post off, I want to remind us where we started. Before treating primes in this abstract, removed way, we started with how we all learned what a prime number is: a number that has no other factors other than 1 and itself. We then recalled the slighlty more useful, still simple and well-known fact that every natural number can be factored as a product of primes, a fact which we summarized with the <strong>natural numbers are a unique factorization domain (UFD)</strong>. But since the natural numbers aren&#39;t the only UFD, this leads to the obvious question: is there a Prime Number Theorem for <em>other</em> UFDs? It turns out, there is.</p>
<p>One of the most common and useful UFDs is the ring of polynomials over a field $K[x]$. That is, if $K$ is a field, then the set $K[x]$ of one-variable polynomials in $x$ with coefficients in $K$ is a UFD. For a quick refresher for why if you know some ring theory, $K[x]$ is a principal ideal domain (PID) due to the division algorithm (which works since $K$ is a field), and every PID is a UFD. Our &quot;primes&quot; in $K[x]$ are not numbers, but rather <em>irreducible polynomials</em> i.e. polynomials that cannot be factored into a product of non-constant polynomials.</p>
<p><strong>Example:</strong> In $\mathbb{R}[x]$, $x^2 + 1$ is irreducible since it has no roots, but in $\mathbb{C}[x]$ factors into irreducibles as $x^2+1 = (x-i)(x+i)$.</p>
<p>For any infinite field, there are an infinite number of irreducible polynomials: just take the linear polynomials $f(x) = x - \alpha$ for $\alpha \in K$, just like how there are an infinite number of primes in $\mathbb{N}$. Since there is no obvious ordering on polynomials, we can&#39;t make a prime counting style function $\pi(x)$ easily for $K[x]$. </p>
<p>However, if we let $K = \mathbb{F}_q$ be the finite field of (prime power) order $q$, and $P_n$ denote the set of monic irreducible polynomials of degree $n$, then it turns out</p>
<center>

$\displaystyle | P_n | = \# \{ \textrm{monic irreducible polynomials of degree } n \} \sim \frac{q^n}{n} = \frac{x}{\log_q x}$

</center>

<p>where we make the substitution $x = q^n$ to highlight the analogy. <a href="https://arxiv.org/pdf/1001.0409">The proof is not super long</a>, but requires knowing some field/Galois theory. On the whole, it is not difficult and the prerequisites can be learned relatively quickly, but are still necessary. In particular for finite fields, <a href="https://kconrad.math.uconn.edu/blurbs/galoistheory/finitefields.pdf">this is a great refresher</a>.</p>
<p><strong>Theorem:</strong> The number of monic irreducible polynomials of degree $n$ over the finite field $\mathbb{F}_q$ is $P_n = \frac{1}{n} \sum_{d \mid n} \mu(n/d) q^d$ where $\mu$ is the Möbius function.</p>
<p><em>Proof:</em> We proceed combinatorially, counting the number of elements of finite fields in two different ways that relate to the size of the set $P_n$. The case for $n=1$ is clear since $| P_1 | = q = \frac{1}{1} \sum_{d \mid 1} \mu(d/1) q^d$ since there are $q$ monic linear polynomials (that are all irreducible) and the only divisor of 1 is 1 itself. So for the remainder of the proof, we assume $n&gt;1$.</p>
<p>Let $R_n = \bigcup \{\textrm{roots of } f(x) \ \mid \ f(x) \in P_n \}$ be the collection of all the roots in $\overline{\mathbb{F}_q}$ of polynomials in $P_n$. Since these irreducible polynomials are of degree $n$, the splitting field for all of these polynomials are $\mathbb{F}_{q^n}$, so we can restrict our attention there. Since irreducible polynomials are minimal polynomials of their roots, we can make use of two properties to characterize $R_n$.</p>
<ul>
<li><strong>Roots of minimal (and so irreducible) polynomials are distinct</strong>: This can be seen by $\mathbb{F}_q$ being the splitting field of the separable polynomial $x^q - x$ and so Galois. More directly since every element satisfies $x^q - x$ by Lagrange&#39;s theorem, take irreducible $f$ with root $\alpha \in \mathbb{F}_q$, so $f(x) \mid x^q - x$ and so is separable.</li>
<li><strong>Distinct irreducible polynomial have distinct roots:</strong> Since each irreducible $f$ is the minimal polynomials of its roots, and minimal polynomials are unique, distinct irreducibles have distinct roots.</li>
</ul>
<!-- Also, note that all roots of irreducible polynomials are distinct (since $\mathbb{F}\_q$ is the splitting field of the separable polynomial $x^q - x$; alternatively, take any irreducible and hence minimal polynomial $f$ with root $\alpha \in \mathbb{F}\_q$, so $f(x) \mid x^q - x$ and so is separable). -->
<p>So $R_n$ is actually the union of disjoint $n$-element sets, one for each polynomial $f(x) \in P_n$ i.e. $\left| R_n \right| = n \left| P_n \right|$. Therefore it is sufficient to count $R_n$ to count $P_n$. Building off the definition of $R_n$:</p>
<center>

$\begin{align}

R_n &amp; = \{ \alpha \in \mathbb{F}_{q^n} \ \mid \ \exists f(x) \in P_n \textrm{ s.t. } f(\alpha) = 0  \} \\
&amp; = \{ \alpha \in \mathbb{F}_{q^n} \ \mid \ \left[ \mathbb{F}_q(\alpha) : \mathbb{F}_q \right] = n \} \\
&amp; = \{ \alpha \in \mathbb{F}_{q^n} \ \mid \ \alpha \textrm{ not contained in any proper subfield of } \mathbb{F}_{q^n} \} \\
&amp; = \{ \alpha \in \mathbb{F}_{q^n} \ \mid \ \alpha \textrm{ not contained in any maximal proper subfield of } \mathbb{F}_{q^n} \} \\

\end{align}$

</center>

<p>The second equality comes from the degree of simple field extensions. The third is for degree reasons from the Tower Law. The fourth follows from $\mathbb{F}_{q^n}/\mathbb{F}_q$ having a finite number of subfields (or more generally from an application of Zorn&#39;s lemma that allows us to extend subfields to maximal ones; also, as <a href="https://proofwiki.org/wiki/Steinitz%27s_Theorem">a result of the Primitive Element Theorem</a> or Fundamental Theorem of Galois Theory, a finite separable field extension can only have finitely many intermediate fields). Note the subfields of $\mathbb{F}_{q^n}$ are $\mathbb{F}_{q^k}$ such that $k \mid n$ (most quickly seen by the Fundamental Theorem of Galois Theory). So writing $n = p_1^{e_1}p_2^{e_2}p_3^{e_3}\cdots p_r^{e_r}$ as its prime factorization, we find that the maximal subfields of $\mathbb{F}_{q^n}$ are</p>
<center>

$\displaystyle F_{p_1} = \mathbb{F}_{q^{n/p_1}} \ , \ \ F_{p_2} = \mathbb{F}_{q^{n/p_2}} \ , \ \ \cdots \ \ , \ \  F_{p_r} = \mathbb{F}_{q^{n/p_r}}$

</center>

<p>Hence, by our final equivalence above, $| R_n | = \left| \mathbb{F}_{q^n} \setminus \left( F_{p_1} \cup F_{p_2} \cup \cdots \cup F_{p_r} \right) \right|$. Also, the lattice of subfields of $\mathbb{F}_{q^n}$ correspond to the lattice of divisors of $n$ (again by the Fundamental Theorem of Galois Theory), so we get the intersections of fields as we would expect with $F_{p_i} \cap F_{p_j} = \mathbb{F}_{q^{n/p_i p_j}}$ (and similarly for intersections of more than 2 fields). So using inclusion-exclusion counting,</p>
<center>

$\begin{align}

\left| \bigcup_{i=1}^r F_{p_i} \right| &amp; = \left( \sum_{i=1}^r | F_{p_i} | \right) - \left( \sum_{1\leq i &lt; j \leq r} | F_{p_i} \cap F_{p_j} | \right) + \cdots + (-1)^{r+1} \left| \bigcap_{i=1}^r F_{p_i} \right| \\
&amp; = \left( \sum_{i=1}^r q^\frac{n}{p_i} \right) - \left( \sum_{1 \leq i &lt; j \leq r} q^\frac{n}{p_i p_j} \right) + \cdots + (-1)^{r+1} q^\frac{n}{p_1 p_2 \cdots p_r}

\end{align}$

<!-- \| F\_{p\_1} \cup F\_{p\_2} \cup \cdots \cup F\_{p\_r} \| 

(-1)^{r+1} \left| F\_{p\_1} \cap F\_{p\_2} \cap \cdots \cap F\_{p\_r} \right|

\| F\_{p\_1} \| \cup \| F\_{p\_2} \| \cup \| \cdots \| \cup \| F\_{p\_r} \| -->


</center>

<p>And so in particular,</p>
<center>

$\displaystyle |R_n | = q^n - \left( \sum_{i=1}^r q^\frac{n}{p_i} \right) + \left( \sum_{1 \leq i &lt; j \leq r} q^\frac{n}{p_i p_j} \right) - \cdots + (-1)^{r} q^\frac{n}{p_1 p_2 \cdots p_r}$

</center>

<p>So dividing by $n$ and applying the Möbius function (noting that $\mu(d) = 0$ for non square-free divisors), we have</p>
<center>

$\displaystyle |P_n | = \frac{1}{n} \sum_{d \mid n} \mu(d) q^{n/d} = \frac{1}{n} \sum_{d \mid n} \mu(n/d) q^{d}$

</center>

<p>We get the last equality since as $d$ runs over all divisors of $n$, so does $n/d$. $\blacksquare$</p>
<p><strong>Corollary:</strong> $|P_n| \sim \frac{q^n}{n}$.</p>
<p><em>Proof:</em> The dominant term in the expression is $q^n/n$, since the next largest power of $q$ in the formula is at most $q^{n/2}$ since the smallest non-trivial divisor of $n$ is at least 2, and thus bound the remaining terms by $o(q^n/n)$. $\blacksquare$</p>
<h2 id="conclusion">Conclusion</h2>
<p>This post, while dense, has only scratched the surface of what primes and the Prime Number Theorem actually has to offer. From other bounds in combinatorics and analysis, to important computational heuristics in cryptography, primes, while random, find their ways into many facets of math. There&#39;s always more to revisit, but that&#39;s all for another day.</p>
<!-- give cool corollary of Bertrand's
generalizations with Sylvester's thm: https://www.renyi.hu/~p_erdos/1934-01.pdf
maybe talk a bit about Chebyshev's proof of Bertrand's postulate to get initial estimates on PNT
show later PNT gives better bounds: always a prime between n and (1+epsilon)n 
PNT shows there are roughly n/log n primes between n and 2n -->
<!-- simple patterns -->
<!-- show cartesian products of N is countable -->
<!-- encoding all the numbers via prime products -> i.e. riemann zeta function -->
   <!-- maybe euler proof of infinite primes -->
<!-- 

* euclid's lemma:
  * basically shows irreducible -> prime -> Z is a UFD
  * in general ring theory, easier to show irreducible <-> prime assuming UFD

* infinitude of primes
* euπ¸clid's lemma
* fundamental theorem of arithmetic
  * elaborate a bit on ring theory and abstract algebra
  * the integers are a UFD, but not Z[√-5]
  * let's us talk about objects with unique decomposition (show Riemann zeta function decomposition)
    * maybe introduce Euler's proof of infinite primes to bring in Riemann zeta function
  * this fundamental encoding shapes a lot (gives proof of N is countable, Gödel's thms, etc)
    * extends naturally to rationals
* build a bit more on relevance of primes and modern results that are easier to understand breaking things down into smaller parts
  * i.e. group theory results, chinese remainder theorem, structure theorem, lagrange's theorem (useful since if we know prime divisors, can infer more probably), characteristic of a field is prime
* Even though the primes look random, we can say a lot about them still
  * simple results: p = 6k ± 1, 24 | p^2 - 1, goldbach's conjecture, idk find more, mersenne primes and perfect numbers, we even have a formula for them
  * there's a dedicated search to finding the next largest prime number (maybe give current record)
    * maybe talk about types of primes (mersenee, fermat, probable, etc)
* Finding Primes and Primality Tests
* We have facts about how the primes are distributed too
* Bertrand's postulate
  * not obvious always: Legendre's conjecture
* Dirichlet's theorem on arithmetic progressions
  * Green-Tao thm: there exist arbitrarily long arithmetic progressions in the primes
  * Extension -> too hard
* Prime number theorem
  * seems hard to think about
  * introduce sieves for some intuition
 -->
]]></description>
         <link>http://xperimex.github.io/blog/prime-number-theorem</link>
         <guid isPermaLink="true">http://xperimex.github.io/blog/prime-number-theorem</guid>
         <dc:creator><![CDATA[Adi Mittal]]></dc:creator>
      </item>
      <item>
         <title><![CDATA[Introductory Quantum Elliptic Curve Cryptography]]></title>
         <description><![CDATA[Actually important online doomsday prepping 

 <p>Previously, I had the opportunity <a href="https://xperimex.com/blog/variational-calculus/">to cap off my high school math career to write and present a topic of my choosing</a>. In that case, I spent a couple weeks looking at the basics of the calculus of variations and its physics-inspired methods. To round off my undergraduate curriculum, I was given a similar opportunity on a much larger scale. Spanning across 2.5 quarters and 55 pages, I spent this past year learning the math that justifies online security for the present and hopefully future. In particular, I spent the time learning the math behind elliptic curve cryptography, and the quantum threats and safeguards that people hope to use once quantum computing becomes powerful enough to break classical methods. This project was mostly motivated by the ever well-known Shor&#39;s algorithm that kicked off this quantum arms race. I was curious what made it so clever and so dangerous, and while the latter is true, I found out it was underwhelmingly just a type of Fourier transform and not much more (which makes sense in hindsight for its goal is to detect &quot;periodicities&quot; in the hidden <a href="https://en.wikipedia.org/wiki/Hidden_subgroup_problem">subgroup problem</a>). I have spent a few <a href="https://xperimex.com/blog/zero-knowledge/">other posts talking about cryptography and the motivating math before</a>, but I&#39;m glad to have put in the time to go to the depth of something like a project like this. In the future, I do want to revisit this topic to some extent, for I took a very computational route to the group theory to make the implementation and calculations clear. However, the abstract algebra approaches that I was dodging for time provided the much stronger results I needed towards the end. Now that I&#39;m more equipped to understand it, there is a lot to properly absorb and unpack, but that&#39;s for later. Below you will find my written report and accompanying slideshow. As I find errors retroactively, I&#39;ll update the files accordingly.</p>
<ul>
<li><a href="/img/quantum-elliptic-curves/BSP_Pre_and_Post_Quantum_Elliptic_Curve_Cryptography.pdf">Written Report</a></li>
<li><a href="/img/quantum-elliptic-curves/BSP_Final_Slides.pdf">Presentation Slides</a></li>
</ul>
]]></description>
         <link>http://xperimex.github.io/blog/quantum-elliptic-curves</link>
         <guid isPermaLink="true">http://xperimex.github.io/blog/quantum-elliptic-curves</guid>
         <dc:creator><![CDATA[Adi Mittal]]></dc:creator>
      </item>
   </channel>
</rss>