<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <generator uri="https://jekyllrb.com/" version="4.3.3">Jekyll</generator>
  <link href="https://ak2316.user.srcf.net/atom.xml" rel="self" type="application/atom+xml"/>
  <link href="https://ak2316.user.srcf.net/" rel="alternate" type="text/html"/>
  <updated>2024-05-03T15:31:46+00:00</updated>
  <id>https://ak2316.user.srcf.net/</id>
  <title type="html">adamkelly</title>
  <subtitle>Lecture Notes, Handouts and Writings of an Undergraduate Mathematics Student at Cambridge.</subtitle>
  <author>
    <name>Adam Kelly</name>
    <email>ak2316@srcf.net</email>
  </author>
  <entry>
    <title type="html">Deriving a PDE For Call Option Prices with Black-Scholes</title>
    <link href="https://ak2316.user.srcf.net/2024/05/black-scholes-pde/" rel="alternate" type="text/html" title="Deriving a PDE For Call Option Prices with Black-Scholes"/>
    <published>2024-05-02T12:25:40+00:00</published>
    <updated>2024-05-02T12:25:40+00:00</updated>
    <id>https://ak2316.user.srcf.net/2024/05/black-scholes-pde</id>
    <content type="html" xml:base="https://ak2316.user.srcf.net/2024/05/black-scholes-pde/"><![CDATA[
        
<h2 id="brownian-motion">Brownian Motion</h2>

<p>The building block of stochastic calculus is <em>Brownian motion</em>, or <em>Weiner process</em>. We take a stochastic process starting at zero that is then defined by independent, Gaussian increments:</p>

<div class="kdmath">$$
\begin{align*}
    B_0 &amp;= 0 \\
    B_t - B_s &amp;\sim N(0, t - s),
\end{align*}
$$</div>

<p>or in shorthand, $dB_t \sim N(0, \delta t)$, where $d B_t$ is the increment and $\delta t$ is the time interval. We care about $\delta t \rightarrow 0$. 
We note that the differences $dB_t$ are all independent if they don’t overlap.</p>

<h2 id="quadratic-variation">Quadratic Variation</h2>

<p>Given a function $f$ we define the <em>quadratic variation</em> to be
<span class="kdmath">$(d f\; d f) = \lim_{\left|\Pi\right| \to 0} \sum_{j = 0}^{n - 1}(f(t_{j + 1}) - f(t_j))^2,$</span>
where $\Pi$ is the sum of the square distance between the intervals on the time grid $t_j$.</p>

<p>If a function is differentiable, the mean value theorem implies that these differences go to zero as the intervals $[t_j, t_{j + 1}]$ 
go to zero. This is however not the case for Brownian motion. Indeed, Brownian motion is continuous but not differentiable (we will not prove this here).</p>

<p><strong>Lemma</strong> (Quadratic Variation of Brownian Motion).
$d B_t \; dB_t = dt$.</p>

<p><em>Proof</em>. Omitted.</p>

<h2 id="covariance">Covariance</h2>

<p>We will now pause to consider the covariance of Brownian motion. We can compute (using our definition above)</p>

<div class="kdmath">$$
\begin{align*}
    \operatorname{Cov} (B_t, B_s) &amp;= \mathbb{E}[B_t B_s] \\
                    &amp;= \mathbb{E}[B_t (B_s - B_t) + B_t^2]\\
                    &amp;= \mathbb{E}[B_t^2] = \min(t, s).
\end{align*}
$$</div>

<h2 id="a-stochastic-differential-equation">A Stochastic Differential Equation</h2>

<p>We want to write down a <em>stochastic differential equation</em> which will define the increments of
a stochastic process $S_t$. We will do this in the form of a <em>drift-diffusion</em> model</p>

<div class="kdmath">$$
dS_t = \mu(S_t, t) dt + \sigma(S_t, t) dW_t,
$$</div>

<p>where $\mu$ and $\sigma$ are arbitrary (non-stochastic) functions defining the <em>drift</em> and <em>volatility</em>.</p>

<p>The <em>Black-Scholes</em> equation is</p>

<div class="kdmath">$$
d S_t = r s_t dt + \sigma S_t dW_t.
$$</div>

<p>We wil find this yields asset prices $S_t$ that are log-normally distributed.</p>

<h2 id="itos-lemma">Ito’s Lemma</h2>

<p>We want to ‘taylor expand’ a stochastic process by using a stochastic differential equation. Suppose we have an SDE of the form above,</p>

<div class="kdmath">$$
dS_t = \mu(S_t, t) dt + \sigma(S_t, t) dW_t,
$$</div>

<p>We want to ignore ‘small’ terms. Normally we would ignore anything smaller than $O(dt)$ and $O(S_t)$, but quadratic variation implies the $d W_t^2$ term will be order $O(d_t)$ and can’t be ignored. So doing this gives us <em>Ito’s Lemma</em>:</p>

<div class="kdmath">$$
df = \frac{\partial f}{\partial t} dt + \frac{\partial f}{\partial S_t} d S_t + \frac{1}{2} \frac{\partial^2 f}{\partial S_t^2} dS_t^2.
$$</div>

<p>For the drift-diffusion model above we have</p>

<div class="kdmath">$$
df = \frac{\partial f}{\partial t} dt + \frac{\partial f}{\partial S_t} \mu(S_t, t) d t + \frac{\partial f}{\partial S_t} \sigma(S_t, t) d W_t + \frac{1}{2} \frac{\partial^2 f}{\partial S_t^2} \sigma(S_t, t)^2 dt.
$$</div>

<h2 id="pricing-a-call-option">Pricing a Call Option</h2>

<p>Now we can put together all of the building blocks above to come up with the price of a call option. We have</p>

<div class="kdmath">$$
dS_t = r S_t dt + \sigma S_t d W_t.
$$</div>

<p>We want to compute the price of the call option with a strike $K$, that is, one whose terminal value is</p>

<div class="kdmath">$$
c(S_T, T) = \max(S_T - K, 0).
$$</div>

<p>We can model this as a stochastic process $c(S_t, t)$ which has the above boundary condition and evolves according to the Black-Scholes equation above.</p>

<p>We want to write down a SDE for $c$. Applying Ito’s Lemma gives us</p>

<div class="kdmath">$$
dc = \left(\frac{\partial c}{\partial t} + \frac{\partial c}{\partial S_t}\mu S_t + \frac{1}{2} \frac{\partial^2 c}{\partial S_t^2} \sigma^2 S_t^2 \right) dt + \frac{\partial c}{\partial S_t} \sigma S_t d W_t
$$</div>

<p>Note that this implies that if we hold the portfolio $\Pi(S_t, t) = c(S_t, t) - \frac{\partial c}{\partial S_t} S_t$, the portfolios is left with no exposure to the ‘randomness’ (Brownian motion) term, and so our portfolio is riskless\footnote{This, you may have guessed, is a delta hedged portfolio.}.</p>

<p>This portfolio evolves according to (after expanding)</p>

<div class="kdmath">$$
\begin{align*}
    d \Pi(S_t, t) = \left(\frac{\partial c}{\partial t} + \frac{1}{2}\sigma^2 S_t^2 \frac{\partial^2 c}{\partial s^2}\right) dt
\end{align*}
$$</div>

<p>Now we already know we have a risk free portfolio, and so it must evolve according to the risk free rate $r$ by</p>

<div class="kdmath">$$
\begin{align*}
    d \Pi(S_t, t) &amp;= r \Pi dt \\
    &amp;= r (c(S_t, t) - \frac{\partial c}{\partial s} S_t) dt
\end{align*}
$$</div>

<p>These models must give us the same result ultimately, and equating them gives</p>

<div class="kdmath">$$
r c(S_t, t) - r\frac{\partial c}{\partial s} S_t = \frac{\partial c}{\partial t} + \frac{1}{2}\sigma^2 S_t^2 \frac{\partial^2 c}{\partial s^2}
$$</div>

<p>This is a PDE describing the price of a call option.</p>


        <p>[If the formatting of this post looks odd in your feed reader, <a href="https://ak2316.user.srcf.net//2024/05/black-scholes-pde/">visit the original article</a>]</p>
        ]]></content>
    <category term="maths"/>
    <category term="finance"/>
    <category term="probability"/>
  </entry>
  <entry>
    <title type="html">Erdős Theorem on Monotone Multiplicative Functions</title>
    <link href="https://ak2316.user.srcf.net/2021/09/erdos-monotone-multiplicative/" rel="alternate" type="text/html" title="Erdős Theorem on Monotone Multiplicative Functions"/>
    <published>2021-09-01T12:25:40+00:00</published>
    <updated>2021-09-01T12:25:40+00:00</updated>
    <id>https://ak2316.user.srcf.net/2021/09/erdos-monotone-multiplicative</id>
    <content type="html" xml:base="https://ak2316.user.srcf.net/2021/09/erdos-monotone-multiplicative/"><![CDATA[
        
<p>In number theory, a <em>totally multiplicative function</em> is a function $f: \mathbb{N} \rightarrow \mathbb{R}$ such that
<span class="kdmath">$f(mn) = f(m)f(n),$</span>
for all $m, n \in \mathbb{N}$.</p>

<p>In 1946, Paul Erdős proved a lovely result<sup id="fnref:1" role="doc-noteref"><a href="#fn:1" class="footnote" rel="footnote">1</a></sup> about such functions, which we are going to prove!</p>

<hr>

<blockquote>
  <p><strong>Theorem</strong>. If $f: \mathbb{N} \rightarrow \mathbb{R}$ is increasing and totally multiplicative, then $f(n) = n^{\alpha}$, for some $\alpha \in \mathbb{R}$.</p>
</blockquote>

<p><em>Proof</em>. Suppose that $f(2) = 2^{\alpha}$, and take $n &gt; 2$ such that $f(n) = n^{\beta}$. Then for any $\ell \in \mathbb{N}$, we can write</p>

<div class="kdmath">$$
2^a &lt; n^{\ell} &lt; 2^{a + 1},
$$</div>

<p>for $a = \lfloor \log_2(n) \ell \rfloor$. Since $f$ is increasing, evaluating the function at each of the above must still satisfy the inequality</p>

<div class="kdmath">$$
\begin{aligned}
2^{\alpha a} &lt; n^{\beta \ell} &amp;&lt; 2^{\alpha(a + 1)} \\
\implies \lfloor \log_2(n) \ell\rfloor &lt; \frac{\beta}{\alpha} \log_2(n) \ell &amp;&lt; \lceil \log_2(n) \ell\rceil.
\end{aligned}
$$</div>

<p>This implies the inequality</p>

<div class="kdmath">$$
\log_2(n) \ell \left|\frac{\beta}{\alpha} - 1\right| \leq 1.
$$</div>

<p>But this has to hold for all $\ell \in \mathbb{N}$, and thus we must have $\beta = \alpha$, and we’re done.</p>

<div class="footnotes" role="doc-endnotes">
  <ol>
    <li id="fn:1" role="doc-endnote">
      <p>He actually proved a slightly different result about <em>additive functions</em>, which you can imagine the definition of, but the results are equivalent by taking logs. See <em>Erdos, P., 1946. On the distribution function of Additive Functions. The Annals of Mathematics, 47(1)</em>. <a href="#fnref:1" class="reversefootnote" role="doc-backlink">↩︎</a></p>
    </li>
  </ol>
</div>


        <p>[If the formatting of this post looks odd in your feed reader, <a href="https://ak2316.user.srcf.net//2021/09/erdos-monotone-multiplicative/">visit the original article</a>]</p>
        ]]></content>
    <category term="maths"/>
    <category term="number-theory"/>
    <category term="analysis"/>
  </entry>
  <entry>
    <title type="html">An Interesting Combinatorial Sum</title>
    <link href="https://ak2316.user.srcf.net/2021/08/combi-sum/" rel="alternate" type="text/html" title="An Interesting Combinatorial Sum"/>
    <published>2021-08-18T01:05:40+00:00</published>
    <updated>2021-08-18T01:05:40+00:00</updated>
    <id>https://ak2316.user.srcf.net/2021/08/combi-sum</id>
    <content type="html" xml:base="https://ak2316.user.srcf.net/2021/08/combi-sum/"><![CDATA[
        
<p>The following problem appeared as part of <a href="https://www.maths.cam.ac.uk/undergrad/pastpapers/files/2021/paperia_4_2021.pdf">this years Part IA exams</a>.</p>

<blockquote>
  <p><strong>Problem</strong>. Show that</p>

  <div class="kdmath">$$
\sum_{r=0}^{n}(-1)^{r}\binom{n}{r}^2 = \begin{cases}
           0 &amp;\mbox{if $n$ is odd}, \\
            (-1)^{n/2} \binom{n}{n/2} &amp;\mbox{if $n$ is even}.
           \end{cases}
$$</div>
</blockquote>

<p>The normal solution involves looking at the coefficient of $x^n$ in the equation</p>

<div class="kdmath">$$
(1-x)^n(1+x)^n=(1-x^2)^n,
$$</div>

<p>but it is possible to solve the problem without resorting to the binomial theorem.</p>

<h2 id="a-combinatorial-solution">A Combinatorial Solution</h2>

<p><em>Solution</em>. 
We begin by noting that</p>

<div class="kdmath">$$
\binom{n}{r}^2 = \binom{n}{r}\binom{n}{n - r}
$$</div>

<p>is the number of ways of choosing $r$ elements from $\{1, \dots, n\}$ followed by $n - r$ elements from $\{n + 1, \dots, 2n\}$. Then as we sum over $r$, the sum (ignoring the minus sign) counts the total number of $n$ element subsets from $\{1, \dots, 2n\}$.</p>

<p>Now to each $n$-element subset of $\{1, \dots, 2n\}$, we assign ‘1’ if the subset contains an even number of elements in $\{1, \dots, n\}$, and a ‘-1’ if it contains an odd number. Summing over all of these assigned numbers then is equivalent to our original sum.</p>

<p>Consider the following mapping. Given a subset of size $n$, let $1 \leq x \leq n$ be the smallest integer for which exactly one of $x, n + x$ is in the set. We then toggle $x$ and $n + x$ in the subset, giving us another subset of $\{1, \dots, 2n\}$ of size $n$, but maps between elements of different sign. It’s also clearly an involution (applying it twice gives you back the original subset).</p>

<p>If $n$ is odd, then this mapping is well defined, since if there was no such element $x$, then $x$ and $n + x$ would always be in the subset, and there would have to then be an even number of elements in the subset (which isn’t the case).
If $n$ is even, then this mapping is only not well defined when we always have both $x$ and $n + x$ in the subset. Thus the mapping is not defined on $\binom{n}{n/2}$ subsets, since we can fully specify each of these by choosing the $n/2$ elements of $\{1, \dots, n\}$ to include. Also all such subsets were given the sign $(-1)^{n/2}$.</p>

<p>Thus if $n$ is odd, we can use this mapping to pair each element with a positive sign to an element with a negative sign, and the total sum is zero. If $n$ is even, then we can do this for all but $\binom{n}{n/2}$ elements, all of which have sign $(-1)^{n/2}$, and thus summing up we get the desired answer,</p>

<div class="kdmath">$$
\sum_{r=0}^{n}(-1)^{r}\binom{n}{r}^2 = \begin{cases}
          0 &amp;\mbox{if $n$ is odd}, \\
           (-1)^{n/2} \binom{n}{n/2} &amp;\mbox{if $n$ is even}.
          \end{cases}
$$</div>


        <p>[If the formatting of this post looks odd in your feed reader, <a href="https://ak2316.user.srcf.net//2021/08/combi-sum/">visit the original article</a>]</p>
        ]]></content>
    <category term="maths"/>
    <category term="combinatorics"/>
    <category term="algebra"/>
    <category term="tripos"/>
  </entry>
  <entry>
    <title type="html">A Short Handout on Hall’s Marriage Theorem</title>
    <link href="https://ak2316.user.srcf.net/2021/08/hall/" rel="alternate" type="text/html" title="A Short Handout on Hall's Marriage Theorem"/>
    <published>2021-08-17T19:12:40+00:00</published>
    <updated>2021-08-17T19:12:40+00:00</updated>
    <id>https://ak2316.user.srcf.net/2021/08/hall</id>
    <content type="html" xml:base="https://ak2316.user.srcf.net/2021/08/hall/"><![CDATA[
        <p>I just uploaded a short handout about Hall’s theorem, with a short proof, some motivation for the result and a few interesting problems from various olympiads/example sheets. <a href="https://ak2316.user.srcf.net/files/handouts/hall/halls-hallway.pdf">Check it out</a>.</p>

        <p>[If the formatting of this post looks odd in your feed reader, <a href="https://ak2316.user.srcf.net//2021/08/hall/">visit the original article</a>]</p>
        ]]></content>
    <category term="maths"/>
    <category term="combinatorics"/>
  </entry>
  <entry>
    <title type="html">Writing a Javascript Module Bundler</title>
    <link href="https://ak2316.user.srcf.net/2021/07/writing-a-module-bundler/" rel="alternate" type="text/html" title="Writing a Javascript Module Bundler"/>
    <published>2021-07-11T15:40:15+00:00</published>
    <updated>2021-07-11T15:40:15+00:00</updated>
    <id>https://ak2316.user.srcf.net/2021/07/writing-a-module-bundler</id>
    <content type="html" xml:base="https://ak2316.user.srcf.net/2021/07/writing-a-module-bundler/"><![CDATA[
        
<p>In this post, we are going to be looking at how to write a really simple Javascript module bundler. First though, we are going to look at what a module bundler actually is.</p>

<p><em>This post draws on <a href="https://slides.com/lucianomammino/unbundling-the-javascript-module-bundler-dublinjs">this talk</a> by Luciano Mammino, and <a href="https://github.com/ronami/minipack">this repo</a> by Ronen Amiel.</em></p>

<h2 id="what-is-a-module-bundler">What is a Module Bundler?</h2>

<p>A module bundler is a tool that takes pieces of JavaScript and their dependencies and bundles them into a single file, usually for use in the browser. You may have used tools such as <a href="http://browserify.org/">Browserify</a>, <a href="https://webpack.js.org/">Webpack</a>, <a href="https://rollupjs.org/guide/en">Rollup</a> or one of many others.</p>

<p>It usually starts with an entry file, and from there it bundles up all of the code needed for that entry file to be able to run.</p>

<p><img src="https://i.imgur.com/KViSEQ0.png" alt="Files and their dependencies are bundled up from an entry point, leaving a single bundled file at the end."></p>

<p>Module bundlers have two main stages:</p>

<ol>
  <li>Dependency resolution</li>
  <li>Packing</li>
</ol>

<p>Starting from an entry point (such as <code class="language-plaintext highlighter-rouge">app.js</code> above), the goal of dependency resolution is to look for all of the dependencies of your code (other pieces of code that it needs to function) and construct a graph (called a dependency graph).
Once this is done, you can then pack or convert your dependency graph into a single file that the application can use.</p>

<p>Let’s start out our code with some imports (I’ll elaborate on the reason later).</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">const</span> <span class="nx">detective</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="dl">'</span><span class="s1">detective</span><span class="dl">'</span><span class="p">)</span>
<span class="kd">const</span> <span class="nx">resolve</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="dl">'</span><span class="s1">resolve</span><span class="dl">'</span><span class="p">).</span><span class="nx">sync</span>
<span class="kd">const</span> <span class="nx">fs</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="dl">'</span><span class="s1">fs</span><span class="dl">'</span><span class="p">)</span>
<span class="kd">const</span> <span class="nx">path</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="dl">'</span><span class="s1">path</span><span class="dl">'</span><span class="p">)</span>
</code></pre></div></div>

<h2 id="dependency-resolution">Dependency Resolution</h2>

<p>We first need to decide how we want to represent a module during the dependency resolution stage.</p>

<h3 id="module-representation">Module Representation</h3>

<p>For each module we need:</p>

<ul>
  <li>The name and an identifier of the file</li>
  <li>Where the file came from (in the file system)</li>
  <li>The code in the file</li>
  <li>What dependencies that file needs</li>
</ul>

<p>A graph structure then would gets built up by recursively checking for dependencies within each file. In JavaScript, the easiest way to represent such a set of data would be an object.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">let</span> <span class="nx">ID</span> <span class="o">=</span> <span class="mi">0</span>
<span class="kd">function</span> <span class="nx">createModuleObject</span><span class="p">(</span><span class="nx">filepath</span><span class="p">)</span> <span class="p">{</span>
  <span class="kd">const</span> <span class="nx">source</span> <span class="o">=</span> <span class="nx">fs</span><span class="p">.</span><span class="nx">readFileSync</span><span class="p">(</span><span class="nx">filepath</span><span class="p">,</span> <span class="dl">'</span><span class="s1">utf-8</span><span class="dl">'</span><span class="p">)</span>
  <span class="kd">const</span> <span class="nx">requires</span> <span class="o">=</span> <span class="nx">detective</span><span class="p">(</span><span class="nx">source</span><span class="p">)</span>
  <span class="kd">const</span> <span class="nx">id</span> <span class="o">=</span> <span class="nx">ID</span><span class="o">++</span>

  <span class="k">return</span> <span class="p">{</span> <span class="nx">id</span><span class="p">,</span> <span class="nx">filepath</span><span class="p">,</span> <span class="nx">source</span><span class="p">,</span> <span class="nx">requires</span> <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>In the piece of code above, we call a function <code class="language-plaintext highlighter-rouge">detective</code> to the dependencies that the given file needs.
<a href="https://github.com/browserify/detective">Detective</a> is a library that can <em>“find all calls to require() no matter how deeply nested”</em>, and using it means we can avoid both parsing the code and looking for <code class="language-plaintext highlighter-rouge">require</code>s in the resulting AST (Abstract Syntax Tree).</p>

<p>One thing to note is that if you try to do something weird like:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>const libName = 'lodash'
const lib = require(libName)
</code></pre></div></div>

<p>the module bundler will not be able to find it (because that would mean executing the code). This behavior is the same in almost all module bundlers.</p>

<p>So what does running this function from the path of a module give?</p>

<p><img src="https://i.imgur.com/6lUymZx.png" alt="Example module bundler output on a given file"></p>

<p>We can see that this is exactly what we wanted to get. The next stage in the process is dependency resolution, but first I want to talk about the <em>module map</em>.</p>

<h3 id="module-map">Module Map</h3>

<p>When importing modules in Node, you can perform relative imports, like <code class="language-plaintext highlighter-rouge">require('./utils')</code>. To allow this behavior, the bundler would need to know what the right <code class="language-plaintext highlighter-rouge">./utils</code> is once everything is packaged. The way this is implemented is with the module map.</p>

<p>Our module object has a unique id key, which will be our ‘source of truth’. When we are performing our dependency resolution, for each module, we will keep a list of the names of what is being required along with their id. This way, we can get the correct module at run-time.</p>

<p>This also means that we can store all of the modules in a non-nested object, using the id as a key.</p>

<p><img src="https://i.imgur.com/DAteuaN.png" alt="Illustration of the module map"></p>

<h3 id="dependency-resolution-1">Dependency Resolution</h3>

<p>The main purpose of this dependency resolution is to start at the root/entry module, and to look for and resolve dependencies recursively.</p>

<p>To make clear what is meant by <em>‘resolve dependencies’</em>, in Node there is a function <code class="language-plaintext highlighter-rouge">require.resolve</code>, and that is used to figure out where the file your module is <code class="language-plaintext highlighter-rouge">require</code>ing is. The need for this to be an explicit process is because we can import both relatively or from a <code class="language-plaintext highlighter-rouge">node_modules</code> folder.
Luckily there’s an npm module named <code class="language-plaintext highlighter-rouge">resolve</code> which implements this algorithm for us. We just have to pass in the dependency and base URL arguments, and it will do all the hard work for us.</p>

<p>We need to carry out this resolution for each dependency of each module in the project. We also need to create the module map that was mentioned earlier. This process is implemented as follows.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nx">getModules</span><span class="p">(</span><span class="nx">entry</span><span class="p">)</span> <span class="p">{</span>
  <span class="kd">const</span> <span class="nx">rootModule</span> <span class="o">=</span> <span class="nx">createModuleObject</span><span class="p">(</span><span class="nx">entry</span><span class="p">)</span>
  <span class="kd">const</span> <span class="nx">modules</span> <span class="o">=</span> <span class="p">[</span><span class="nx">rootModule</span><span class="p">]</span>

  <span class="c1">// Iterate over the modules, even when new </span>
  <span class="c1">// ones are being added</span>
  <span class="k">for</span> <span class="p">(</span><span class="kd">const</span> <span class="nx">module</span> <span class="k">of</span> <span class="nx">modules</span><span class="p">)</span> <span class="p">{</span>
    <span class="nx">module</span><span class="p">.</span><span class="nx">map</span> <span class="o">=</span> <span class="p">{}</span> <span class="c1">// Where we will keep the module maps</span>

    <span class="nx">module</span><span class="p">.</span><span class="nx">requires</span><span class="p">.</span><span class="nx">forEach</span><span class="p">(</span><span class="nx">dependency</span> <span class="o">=&gt;</span> <span class="p">{</span>
      <span class="kd">const</span> <span class="nx">basedir</span> <span class="o">=</span> <span class="nx">path</span><span class="p">.</span><span class="nx">dirname</span><span class="p">(</span><span class="nx">module</span><span class="p">.</span><span class="nx">filepath</span><span class="p">)</span>
      <span class="kd">const</span> <span class="nx">dependencyPath</span> <span class="o">=</span> <span class="nx">resolve</span><span class="p">(</span><span class="nx">dependency</span><span class="p">,</span> <span class="p">{</span> <span class="nx">basedir</span> <span class="p">})</span>

      <span class="kd">const</span> <span class="nx">dependencyObject</span> <span class="o">=</span> <span class="nx">createModuleObject</span><span class="p">(</span><span class="nx">dependencyPath</span><span class="p">)</span>

      <span class="nx">module</span><span class="p">.</span><span class="nx">map</span><span class="p">[</span><span class="nx">dependency</span><span class="p">]</span> <span class="o">=</span> <span class="nx">dependencyObject</span><span class="p">.</span><span class="nx">id</span>
      <span class="nx">modules</span><span class="p">.</span><span class="nx">push</span><span class="p">(</span><span class="nx">dependencyObject</span><span class="p">)</span>
    <span class="p">})</span>
  <span class="p">}</span>

  <span class="k">return</span> <span class="nx">modules</span>
<span class="p">}</span>
</code></pre></div></div>

<p>At the end of this function, we are left with an array named <code class="language-plaintext highlighter-rouge">modules</code> which will contain module objects for every module/dependency in our project.
With that in place, we can move on to the final step: packing.</p>

<h2 id="packing">Packing</h2>

<p>In the browser, there’s not really such thing as modules, and there’s also no <code class="language-plaintext highlighter-rouge">require</code> or <code class="language-plaintext highlighter-rouge">module.exports</code>. So even though we have all of our dependencies, we currently have no way to use them as modules.</p>

<h3 id="module-factory-function">Module Factory Function</h3>

<p>Enter the factory function.
A factory function is a function (that’s not a constructor) which returns an object. It is a pattern from object oriented programming, and one of its uses is to do encapsulation and dependency injection, which is exactly what we want to do.
Using a factory function, we can both inject our own require function and module.exports object that can be used in our bundled code and give the module its own scope.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// A factory function - we can replace require and module with</span>
<span class="c1">// our own dependency injection</span>
<span class="p">(</span><span class="nx">require</span><span class="p">,</span> <span class="nx">module</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="cm">/* Module Source */</span>
<span class="p">}</span>
</code></pre></div></div>

<p>For each module object obtained in the previous stage, we are going to going to transform it so that a factory function can be used.</p>

<p><img src="https://i.imgur.com/moN6kBq.png" alt="Transforming the module object"></p>

<h3 id="packing-1">Packing</h3>

<p>We are now ready to perform the packing stage.
The main process performed here is putting each module into a module factor function, and then doing dependency injection using the module map.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nx">pack</span><span class="p">(</span><span class="nx">modules</span><span class="p">)</span> <span class="p">{</span>
  <span class="kd">const</span> <span class="nx">modulesSource</span> <span class="o">=</span> <span class="nx">modules</span><span class="p">.</span><span class="nx">map</span><span class="p">(</span><span class="nx">module</span> <span class="o">=&gt;</span> 
    <span class="s2">`</span><span class="p">${</span><span class="nx">module</span><span class="p">.</span><span class="nx">id</span><span class="p">}</span><span class="s2">: {
      factory: (module, require) =&gt; {
        </span><span class="p">${</span><span class="nx">module</span><span class="p">.</span><span class="nx">source</span><span class="p">}</span><span class="s2">
      },
      map: </span><span class="p">${</span><span class="nx">JSON</span><span class="p">.</span><span class="nx">stringify</span><span class="p">(</span><span class="nx">module</span><span class="p">.</span><span class="nx">map</span><span class="p">)}</span><span class="s2">
    }`</span>
  <span class="p">).</span><span class="nx">join</span><span class="p">()</span>

  <span class="k">return</span> <span class="s2">`(modules =&gt; {
    const require = id =&gt; {
      const { factory, map } = modules[id]
      const localRequire = name =&gt; require(map[name])
      const module = { exports: {} }
      factory(module, localRequire)
      return module.exports
    }
    require(0)
  })({ </span><span class="p">${</span><span class="nx">modulesSource</span><span class="p">}</span><span class="s2"> })`</span>
<span class="p">}</span>
</code></pre></div></div>

<p>The final output is an IIFE, which means that if you run that code in the browser (or anywhere else), the function will be run immediately. The IFFE is also a good way to encapsulate scope, so that we don’t pollute everything with all of our modules.</p>

<p>We also inject two kinds of require functions, <code class="language-plaintext highlighter-rouge">require</code> and <code class="language-plaintext highlighter-rouge">localRequire</code>.
The first accepts the id of a module object, but of course the source code isn’t written using ids. Instead, we are using the other function localRequire to take any arguments to require by the modules and convert them to the correct id. This is using those module maps discussed earlier.</p>

<p>Lastly, we call require(0) to require the module with an id of 0, which is our entry file. And that’s it! Our module bundler is 100% complete!</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">module</span><span class="p">.</span><span class="nx">exports</span> <span class="o">=</span> <span class="nx">entry</span> <span class="o">=&gt;</span> <span class="nx">pack</span><span class="p">(</span><span class="nx">getModules</span><span class="p">(</span><span class="nx">entry</span><span class="p">))</span> 
</code></pre></div></div>

<h2 id="congratulations-">Congratulations! 🎉</h2>

<p>So we now have a working module bundler.</p>

<p>This probably shouldn’t be used in production, because it’s missing loads of features (like managing circular dependencies, making sure each file gets only parsed once, es-modules, and so on) but this has hopefully given you a good idea of how module bundlers actually work.</p>

<p>In fact, this one works in about 60 lines if you remove all of the comments.
Thanks for reading, and I hope you have enjoyed a look into the workings of our simple module bundler.</p>

<p>Check out the finished source code at <a href="https://github.com/adamisntdead/wbpck-bundler">https://github.com/adamisntdead/wbpck-bundler</a>.</p>


        <p>[If the formatting of this post looks odd in your feed reader, <a href="https://ak2316.user.srcf.net//2021/07/writing-a-module-bundler/">visit the original article</a>]</p>
        ]]></content>
    <category term="programming"/>
  </entry>
  <entry>
    <title type="html">The 5/8 Theorem – Maximum Probability of Group Elements Commuting</title>
    <link href="https://ak2316.user.srcf.net/2021/06/5-over-8-theorem/" rel="alternate" type="text/html" title="The 5/8 Theorem -- Maximum Probability of Group Elements Commuting"/>
    <published>2021-06-26T15:40:15+00:00</published>
    <updated>2021-06-26T15:40:15+00:00</updated>
    <id>https://ak2316.user.srcf.net/2021/06/5-over-8-theorem</id>
    <content type="html" xml:base="https://ak2316.user.srcf.net/2021/06/5-over-8-theorem/"><![CDATA[
        
<p>Today we are going to attack a group theory problem that has a little bit of a combinatorial flavour.</p>

<blockquote>
  <p><strong>Problem</strong>. Find an upper bound on the maximum probability that two randomly chosen elements of a finite non-abelian group commute, and show that it is attained.</p>
</blockquote>

<h2 id="discussion">Discussion</h2>

<p>Suppose that we have a group $G$, and a random element $g \in G$. We have then got two cases.</p>

<ol>
  <li>If $g$ commutes with everything, then the probability that $g$ commutes with another element is obviously 1.</li>
  <li>If $g$ does not commute with everything, we need to find the probability that it commutes with a random other element.</li>
</ol>

<p>This gives us two things to compute (or more correctly, to bound): the probability that a random element commutes with everything, and the probability that if it does not commute with everything, then it commutes with a random element.
The natural approach is then clearly thinking about centers and centralisers.</p>

<h2 id="solution">Solution</h2>

<p>Let $G$ be a finite group. If it is non-abelian, then its center $Z(G)$ is not the entire group, that is, $G$ has some element $g \not \in Z(G)$.
Then $C_G(g)$, centraliser of $g$, also cannot be the entire group, as that would contradict $z \not \in Z(G)$.</p>

<p>Noting that $C_G(g) \leq G$, and $Z(G) \leq C_G(g)$, we can then apply Lagrange’s theorem twice to get</p>

<div class="kdmath">$$
|Z(G)| \leq \frac{1}{2} |C_G(g)| \leq \frac{1}{4}|G|.
$$</div>

<p>Now let $x$, $y$ be a random elements of $G$. We can bound the probability that they commute with</p>

<div class="kdmath">$$
\mathbb{P}(x\in Z(G)) + \mathbb{P}(x \not \in Z(G)) \cdot \mathbb{P}(y \in C_G(x)) \leq \frac{1}{4} + \frac{3}{4} \cdot \frac{1}{2} = \frac{5}{8}.
$$</div>

<p>This bound is achieved by the Quaternion group $Q_8$.</p>


        <p>[If the formatting of this post looks odd in your feed reader, <a href="https://ak2316.user.srcf.net//2021/06/5-over-8-theorem/">visit the original article</a>]</p>
        ]]></content>
    <category term="maths"/>
    <category term="groups"/>
  </entry>
  <entry>
    <title type="html">Some Examples and Counterexamples in Group Theory</title>
    <link href="https://ak2316.user.srcf.net/2021/06/examples-in-groups/" rel="alternate" type="text/html" title="Some Examples and Counterexamples in Group Theory"/>
    <published>2021-06-25T19:40:15+00:00</published>
    <updated>2021-06-25T19:40:15+00:00</updated>
    <id>https://ak2316.user.srcf.net/2021/06/examples-in-groups</id>
    <content type="html" xml:base="https://ak2316.user.srcf.net/2021/06/examples-in-groups/"><![CDATA[
        
<p>This is a collection of groups that have specific interesting
properties, such as being a counterexample to some non-obvious
statements about groups. Most of these are well known.</p>

<ul>
  <li>
<strong>A group isomorphic to every non-trivial subgroup</strong>. $\mathbb{Z}$.</li>
  <li>
<strong>A group of order $n$ which has no subgroup of $k$, where $k \mid n$</strong>.
$A_5$, since it is simple and thus has no subgroup of index 2. Another
example is $A_4$ (which is the smallest such group), but it’s a little
harder to show that it works.</li>
  <li>
<strong>Two non-isomorphic groups with the same order type</strong>. $C_4 \times C_4$
and $C_2 \times Q_8$. Both have 1 element of order 1, 3 elements of
order 2, and 12 elements of order 4. If this property holds for two
abelian groups, then they are isomorphic.</li>
  <li>
<strong>A non-abelian group with all non-identity elements of order $p$</strong>. The
group of upper triangular $3 \times 3$ matrices over $\mathbb{Z}/p\mathbb{Z}$ with 1s on
the diagonal.</li>
  <li>
<strong>A non-abelian group of order $p^3$</strong>. Same as above.</li>
  <li>
<strong>An infinite group whose proper subgroups are all finite</strong>. The group
$\left\{k/2^{n} : k, n \in \mathbb{N}, k&lt;2^{n}\right\}$ with addition
modulo 1. This is the Prüfer $2$-group.</li>
  <li>
<strong>A group $G$ with $N \trianglelefteq G$ and $H \trianglelefteq N$ such that
$H \not \trianglelefteq G$</strong>. In $D_8$, we have
$\langle s \rangle \trianglelefteq \langle r^2, s \rangle \trianglelefteq \langle r, s \rangle = D_4$,
but $\langle s \rangle \not \trianglelefteq D_4$.</li>
  <li>
<strong>A group in which every group generated by $n$ elements has a
surjective homomorphism to it</strong>. The free group with a basis of $n$
elements.</li>
  <li>
<strong>An infinite group with every non-identity element of order 2</strong>.
$C_2 \times C_2 \times C_2 \times \cdots$.</li>
  <li>
<strong>An infinite non-abelian group with every element of finite order</strong>.
$S_3 \times C_2 \times C_2 \times \cdots$.</li>
  <li>
<strong>A group $G$ with $G \cong G \times G$</strong>.
$G = C_2 \times C_2 \times C_2 \times \cdots$. We can also get
$G \cong G \times G \times G \times \cdots$ in the natural way.</li>
  <li>
<strong>Two non-zero elements of $\mathbb{R}$ that generate a subgroup not isomorphic
to $\mathbb{Z}$</strong>. $1$ and $\sqrt{2}$.</li>
  <li>
<strong>A group with two subgroups whose product is not a subgroup</strong>. Consider
$D_3$, with the distinct reflections $s, s’ \in D_3$. Then
${e, s} \times {e, s’} \not \leq D_3$.</li>
  <li>
<strong>A quotient group of a finite group that is not isomorphic to a
subgroup</strong>. $Q_8 / {-1, 1}$.</li>
  <li>
<strong>A group isomorphic to its automorphism group</strong>.
$S_3 \cong \operatorname{Aut}(S_3)$.</li>
  <li>
<strong>A non-abelian infinite group where the set of elements of finite order
is a subgroup</strong>. $\operatorname{GL}_2(\mathbb{Q})$. We note that this also holds for all
abelian groups, and indeed any group where the elements of finite order
commute with each other.</li>
  <li>
<strong>A group that is not a semi-direct product</strong>. $Q_8$.</li>
  <li>
<strong>A group $G$ with two isomorphic subgroups $H, K$ where $G/H$ and $G/K$
are not isomorphic</strong>. Take $G = C_4 \times C_2$, with
$H = \langle (2, 0) \rangle$ and $K = \langle (0, 1)\rangle$. Then
$G/H \cong C_2 \times C_2$, and $G/K \cong C_4$.</li>
</ul>


        <p>[If the formatting of this post looks odd in your feed reader, <a href="https://ak2316.user.srcf.net//2021/06/examples-in-groups/">visit the original article</a>]</p>
        ]]></content>
    <category term="maths"/>
    <category term="groups"/>
  </entry>
  <entry>
    <title type="html">Welcome!</title>
    <link href="https://ak2316.user.srcf.net/2021/06/welcome/" rel="alternate" type="text/html" title="Welcome!"/>
    <published>2021-06-25T14:49:15+00:00</published>
    <updated>2021-06-25T14:49:15+00:00</updated>
    <id>https://ak2316.user.srcf.net/2021/06/welcome</id>
    <content type="html" xml:base="https://ak2316.user.srcf.net/2021/06/welcome/"><![CDATA[
        <p>Welcome to my new blog! This is hopefully going to be filled with more interesting stuff soon. While you’re waiting, make sure to have a look at my <a href="https://ak2316.user.srcf.net/lecture-notes/">lecture notes</a> and <a href="https://ak2316.user.srcf.net/olympiads/">olympiad materials</a> – hopefully you will find something of use!</p>

        <p>[If the formatting of this post looks odd in your feed reader, <a href="https://ak2316.user.srcf.net//2021/06/welcome/">visit the original article</a>]</p>
        ]]></content>
    <category term="chat"/>
  </entry>
</feed>

