<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>heiner.ai</title>
    <description></description>
    <link>https://heiner.ai/</link>
    <atom:link href="https://heiner.ai/feed.xml" rel="self" type="application/rss+xml"/>
    <pubDate>Wed, 02 Sep 2026 16:18:26 +0000</pubDate>
    <lastBuildDate>Wed, 02 Sep 2026 16:18:26 +0000</lastBuildDate>
    <generator>Jekyll v3.10.0</generator>
    
      <item>
        <title>Random samples</title>
        <description>&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#random-sampling-question-version-1&quot; id=&quot;markdown-toc-random-sampling-question-version-1&quot;&gt;Random sampling question, version 1&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#monte-carlo-solution-aka-rejection-sampling&quot; id=&quot;markdown-toc-monte-carlo-solution-aka-rejection-sampling&quot;&gt;Monte Carlo solution (aka rejection sampling)&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#naive-deletion&quot; id=&quot;markdown-toc-naive-deletion&quot;&gt;Naive deletion&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#keeping-track-of-gaps&quot; id=&quot;markdown-toc-keeping-track-of-gaps&quot;&gt;Keeping track of gaps?&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#swapping-to-the-end&quot; id=&quot;markdown-toc-swapping-to-the-end&quot;&gt;Swapping to the end&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#via-partial-shuffle&quot; id=&quot;markdown-toc-via-partial-shuffle&quot;&gt;Via partial shuffle&lt;/a&gt;        &lt;ul&gt;
          &lt;li&gt;&lt;a href=&quot;#a-fun-side-quest&quot; id=&quot;markdown-toc-a-fun-side-quest&quot;&gt;A fun side quest&lt;/a&gt;&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#floyds-algorithm&quot; id=&quot;markdown-toc-floyds-algorithm&quot;&gt;Floyd’s algorithm&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#version-2-on-solutions&quot; id=&quot;markdown-toc-version-2-on-solutions&quot;&gt;Version 2: \(O(N)\) solutions&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#streams-of-known-length&quot; id=&quot;markdown-toc-streams-of-known-length&quot;&gt;Streams of known length&lt;/a&gt;        &lt;ul&gt;
          &lt;li&gt;&lt;a href=&quot;#selection-sampling&quot; id=&quot;markdown-toc-selection-sampling&quot;&gt;Selection sampling&lt;/a&gt;&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#streams-of-unknown-length&quot; id=&quot;markdown-toc-streams-of-unknown-length&quot;&gt;Streams of unknown length&lt;/a&gt;        &lt;ul&gt;
          &lt;li&gt;&lt;a href=&quot;#heaps&quot; id=&quot;markdown-toc-heaps&quot;&gt;Heaps&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#quickselect&quot; id=&quot;markdown-toc-quickselect&quot;&gt;Quickselect&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#reservoir-sampling&quot; id=&quot;markdown-toc-reservoir-sampling&quot;&gt;Reservoir sampling&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#reservoir-sampling-with-skipping-ahead&quot; id=&quot;markdown-toc-reservoir-sampling-with-skipping-ahead&quot;&gt;Reservoir sampling with skipping ahead&lt;/a&gt;&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#online-shuffling&quot; id=&quot;markdown-toc-online-shuffling&quot;&gt;Online shuffling&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#block-ciphers&quot; id=&quot;markdown-toc-block-ciphers&quot;&gt;Block ciphers&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#pseudorandom-permutations&quot; id=&quot;markdown-toc-pseudorandom-permutations&quot;&gt;Pseudorandom permutations&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#is-0-enough&quot; id=&quot;markdown-toc-is-0-enough&quot;&gt;Is 0% enough?&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#cheap-parameterized-permutations&quot; id=&quot;markdown-toc-cheap-parameterized-permutations&quot;&gt;Cheap parameterized permutations&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I’m going to describe my favorite interview question and then ad-lib a
bit on it. The question has a somewhat mathematical bent but connects
to several practical problems I had in my career.
I used it many dozens of times when interviewing for xAI and other places,
to the extent that it’s slightly worn out (apparently it was asked at
Google &lt;a href=&quot;https://x.com/cosminnegruseri/status/2089789693730951539?s=20&quot;&gt;going back to at least
2005&lt;/a&gt;
and unsurprisingly is on &lt;a href=&quot;https://leetcode.com/problem-list/reservoir-sampling/&quot;&gt;actual
leetcode&lt;/a&gt;). However,
as per the &lt;a href=&quot;/blog/2026/08/18/leetcode.html&quot;&gt;last blog post&lt;/a&gt;, I don’t
think I am giving “too much away” by
describing it here, and I may well use this question again. If
candidates read this, all the better – we can dive in deep then. And
if they have not, despite knowing I’d interview them, that’s an ever so
weak signal too.&lt;/p&gt;

&lt;p&gt;I first heard this question when Greg Chanan interviewed me for FAIR
in 2018. I probably did okay-but-not-great. I did end up getting
an offer and I did join Facebook (renamed to Meta while I was there) in
early 2019.&lt;/p&gt;

&lt;p&gt;Without further ado, here’s the question in its first variant.&lt;/p&gt;

&lt;h2 id=&quot;random-sampling-question-version-1&quot;&gt;Random sampling question, version 1&lt;/h2&gt;

&lt;blockquote&gt;
  &lt;p&gt;Given an array &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;L&lt;/code&gt; of length &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;N&lt;/code&gt; and a number &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;k&lt;/code&gt; with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0 &amp;lt;= k &amp;lt;= N&lt;/code&gt;,
sample &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;k&lt;/code&gt; elements from &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;L&lt;/code&gt;, uniformly and without replacement.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;I typically would suggest some kind of source of randomness, e.g. the
Python standard library functions
&lt;a href=&quot;https://docs.python.org/3/library/random.html#random.random&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;random.random&lt;/code&gt;&lt;/a&gt;
and
&lt;a href=&quot;https://docs.python.org/3/library/random.html#random.randrange&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;random.randrange&lt;/code&gt;&lt;/a&gt;,
with the following behavior:&lt;sup id=&quot;fnref:randrange&quot; role=&quot;doc-noteref&quot;&gt;&lt;a href=&quot;#fn:randrange&quot; class=&quot;footnote&quot; rel=&quot;footnote&quot;&gt;1&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;

&lt;dl&gt;
&lt;dt&gt;&lt;tt&gt;random.random()&lt;/tt&gt;&lt;/dt&gt;
&lt;dd&gt;Return the next random floating-point number in the range &lt;code class=&quot;docutils literal notranslate&quot;&gt;&lt;span class=&quot;pre&quot;&gt;0.0&lt;/span&gt;
&lt;span class=&quot;pre&quot;&gt;&amp;lt;=&lt;/span&gt; &lt;span class=&quot;pre&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;pre&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;pre&quot;&gt;1.0&lt;/span&gt;&lt;/code&gt;&lt;/dd&gt;

&lt;dt&gt;&amp;nbsp;&lt;/dt&gt;

&lt;dt&gt;&lt;tt&gt;random.randrange(stop)&lt;/tt&gt;&lt;/dt&gt;
&lt;dd&gt;Return a randomly selected element from
&lt;tt&gt;range(stop)&lt;/tt&gt;.
&lt;/dd&gt;
&lt;/dl&gt;

&lt;p&gt;Some candidates want an explanation of the terms: “uniform” means
every entry of the array has the same chance of being sampled;
“without replacement” means elements are discarded after being sampled
and cannot be sampled again: in the “urn model”, the balls taken out
of the urn are not being put back into the urn, so they are not being
replaced.&lt;/p&gt;

&lt;p&gt;This opens the door to another question: What is a “same element”
for the purpose of this question? It’s overall more interesting if
there’s no object equality check a la &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;__eq__&lt;/code&gt; in Python here but
instead all elements of the array can be assumed to be unique. This also
implies their index is the only thing that matters, and what the
elements of the array are is otherwise not important.&lt;/p&gt;

&lt;h3 id=&quot;monte-carlo-solution-aka-rejection-sampling&quot;&gt;Monte Carlo solution (aka rejection sampling)&lt;/h3&gt;

&lt;p&gt;A first attempt to solve this could look like&lt;sup id=&quot;fnref:style&quot; role=&quot;doc-noteref&quot;&gt;&lt;a href=&quot;#fn:style&quot; class=&quot;footnote&quot; rel=&quot;footnote&quot;&gt;2&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;random&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;randrange&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;result&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;set&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;result&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;result&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;add&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;randrange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))])&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;result&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This is decent if &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;k/N&lt;/code&gt; is a small number but catastrophically
slow when &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;k&lt;/code&gt; is close to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;N&lt;/code&gt;. However, in the case &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;k/N &amp;gt;= 0.5&lt;/code&gt; one
can choose to sample &lt;em&gt;rejected&lt;/em&gt; instead of &lt;em&gt;selected&lt;/em&gt; items and
arrive at a decent solution overall. This way, the algorithm makes
progress in each iteration with probability \(\ge 0.5\), which means the
chance of &lt;em&gt;not&lt;/em&gt; making progress after \(m\) steps decays exponentially
in \(m\). Note though that the worst case
time complexity is still unbounded (“\(O(\infty)\)”).&lt;/p&gt;

&lt;p&gt;That’s good enough for most practical applications – but not good
enough for a coding interview. So let’s say we are looking for a
solution with deterministic complexity.&lt;/p&gt;

&lt;h3 id=&quot;naive-deletion&quot;&gt;Naive deletion&lt;/h3&gt;

&lt;p&gt;One solution that maps well to “don’t replace balls in the urn”
is simply&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;result&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;randrange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;result&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;del&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;result&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;In place of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;del L[j]&lt;/code&gt;, some people even go for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;L = L[: j] + L[j +
1 :]&lt;/code&gt;. If they have more Python knowledge they might propose&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;result&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;result&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;randrange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))))&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;result&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;All of these are correct solutions, but they suffer from a similar
problem. In order to delete an element of an array &lt;em&gt;while keeping
\(O(1)\) lookups in place&lt;/em&gt;, deletion requires &lt;em&gt;shifting all later
elements&lt;/em&gt; which is \(O(N)\).&lt;/p&gt;

&lt;p&gt;In memory, an array is a buffer that starts at &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;start_ptr&lt;/code&gt; and ends at
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;start_ptr + buffer_len&lt;/code&gt;:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;[ a b c d e f g h i j k l m ]
  ^                         ^
  start_ptr                 |
       start_ptr + buffer_len
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Looking up the element at index &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;i&lt;/code&gt; means resolving
a pointer to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;start_ptr + i&lt;/code&gt;. This makes lookups \(O(1)\) and
cheap even within that class.&lt;/p&gt;

&lt;p&gt;Deleting an element – say, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;g&lt;/code&gt; – creates a hole:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;[ a b c d e f _ h i j k l m ]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The only way to keep simple \(O(1)\) lookups is to shift later
elements into the hole:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;[ a b c d e f h _ i j k l m ]
                  &amp;lt;

[ a b c d e f h i _ j k l m ]
                    &amp;lt;

[ a b c d e f h i j _ k l m ]
                      &amp;lt;

etc.
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This makes deletion shift \(N/2\) elements on average and \(O(N)\).&lt;/p&gt;

&lt;p&gt;Note that a Python &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;list&lt;/code&gt; is also just such a buffer in memory with a
physical capacity and a logical length. When it needs to grow
beyond its capacity a new buffer is created and all elements (which
are pointers of type &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PyObject*&lt;/code&gt;) are copied. Candidates often &lt;em&gt;think&lt;/em&gt; they
don’t know that that is the case but they typically can infer this once
the “contract” of the list is pointed out, which is that random
access is \(O(1)\). There is simply no alternative to an array under
this contract! See
&lt;a href=&quot;https://github.com/python/cpython/blob/main/Objects/listobject.c&quot;&gt;listobject.c&lt;/a&gt;
in the CPython source for the details.&lt;/p&gt;

&lt;h3 id=&quot;keeping-track-of-gaps&quot;&gt;Keeping track of gaps?&lt;/h3&gt;

&lt;p&gt;Some people, myself included, find it natural to try
to track already selected elements. In step &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;i&lt;/code&gt;, one could attempt to
sample from &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;randrange(N - i)&lt;/code&gt; and then add the number of gaps already
chosen left of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;i&lt;/code&gt;. While natural, this is complicated and yields at
best some kind of tree structure and an \(O(k \log k)\) solution, while
\(O(k)\) should be and is possible.&lt;/p&gt;

&lt;p&gt;Some folks propose all kinds of dictionary/hash map approaches, most
of which fail (with an exception, not realistically findable in an
interview, see below!). The fundamental problem is that arrays allow
\(O(1)\) lookup of the \(i\)th element but require \(O(N)\) deletions,
while hash maps &lt;em&gt;might&lt;/em&gt; allow for \(O(1)\) deletions but looking up
the \(i\)th element costs \(O(N)\). Hash maps generally are somewhat
overused due to their convenience. Some
candidates have a really hard time giving them up for this problem.&lt;/p&gt;

&lt;h3 id=&quot;swapping-to-the-end&quot;&gt;Swapping to the end&lt;/h3&gt;

&lt;p&gt;Still, modifying the array is promising, and candidates often find a
better solution when they are explicitly told that’s an okay thing to
do. For instance, one could do&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;random&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;randrange&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;N&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;result&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;randrange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;N&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Take element j, then move in element from the end.
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;result&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;N&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;result&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Note that &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;L[j] = L[N - i - 1]&lt;/code&gt; can be a no-op if the sampled index
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;j&lt;/code&gt; was the end.&lt;/p&gt;

&lt;p&gt;This is an example of a “swap with the end” trick that’s useful more
generally. With swapping instead of moving one can also avoid the
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;result&lt;/code&gt; array:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;random&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;randrange&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;N&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;randrange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;N&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;N&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;N&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;N&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This is pretty short and \(O(k)\) in time with essentially no extra
space, assuming the slice at the end doesn’t create a copy – true if
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;L&lt;/code&gt; is an object like a NumPy array but not true for plain Python
lists. If &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;k&lt;/code&gt; is nonzero, the slice at the end can be written
as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;L[-k :]&lt;/code&gt; but that fails for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;k == 0&lt;/code&gt;.&lt;/p&gt;

&lt;h3 id=&quot;via-partial-shuffle&quot;&gt;Via partial shuffle&lt;/h3&gt;

&lt;p&gt;Sometimes candidates find that “shuffle the list and take the first
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;k&lt;/code&gt; items” is a more intuitive solution:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;shuffle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The question then is how to shuffle. A moment’s reflection shows
that “go through all slots and swap with a random one” is promising:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;shuffle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;randrange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The logic of this algorithm (known as Fisher-Yates in the literature)
is to keep a range of not-yet-chosen elements that is initially the
full array and then shrinks from the left by one element each
iteration. (Since the last random “choice” is choosing from the
one-element &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;range(1)&lt;/code&gt;, the loop could actually use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;range(len(L) - 1)&lt;/code&gt;.)&lt;/p&gt;

&lt;p&gt;This has the nice property that each to-be-filled slot is chosen
once and then the algorithm sticks to its choice.&lt;/p&gt;

&lt;p&gt;It can be turned into a “partial shuffle” where one stops after &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;k&lt;/code&gt;
slots:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;shuffle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;randrange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;With this, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;shuffle(L, k)&lt;/code&gt; and then returning &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;L[: k]&lt;/code&gt; is equivalent to
the swapping-to-the-end solution, but easier to find for some people.&lt;/p&gt;

&lt;h4 id=&quot;a-fun-side-quest&quot;&gt;A fun side quest&lt;/h4&gt;

&lt;p&gt;Here’s a side question: What if we don’t stick with our choices, but
instead allow the full array to be selected every time? This way we
potentially swap already chosen elements:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;alt_shuffle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;randrange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;As an algorithm, this feels worse – for instance, the original
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;shuffle&lt;/code&gt; allows us to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;yield&lt;/code&gt; results as they come. But is it any
worse otherwise? Is it correct? Are both &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;shuffle&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;alt_shuffle&lt;/code&gt;
correct, or only one of them? Or, less plausibly, neither?&lt;/p&gt;

&lt;details&gt;
  &lt;summary&gt;Click here to find out about &lt;tt&gt;shuffle&lt;/tt&gt; vs. &lt;tt&gt;alt_shuffle&lt;/tt&gt;.&lt;/summary&gt;
  &lt;p&gt;It turns out, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;alt_shuffle&lt;/code&gt; is wrong in that it doesn’t result in a
&lt;em&gt;uniform&lt;/em&gt; shuffle.&lt;/p&gt;

  &lt;p&gt;This is true in general for \(N\ge 3\) but one easy way to see this is
to assume that \(k = N = p\) for a prime number \(p &amp;gt; 2\). The number
of different random inputs from &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;randrange&lt;/code&gt; for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;shuffle&lt;/code&gt; is exactly
\(N(N-1)\cdots 1 = N!\). This is also the number of random
permutations of \(N\) items; the algorithm is selecting
one such permutation, step by step.&lt;/p&gt;

  &lt;p&gt;For &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;alt_shuffle&lt;/code&gt;, the number of different random inputs the
algorithm uses is \(N^N\). That is a vastly larger number than
\(N!\), but that by itself doesn’t mean &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;alt_shuffle&lt;/code&gt; is
incorrect, assuming the \(N^N\) random choices can be mapped to
\(N!\) choices in a way that divides the \(N^N\) choices evenly. However, the
expression \(N!\) has prime factors for every prime up to \(N\), while
\(N^N\) only has \(p\) as a prime factor. \(N^N\) isn’t divisible by
\(N!\) (that is, \(N^N/N!\) is not an integer). This means &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;alt_shuffle&lt;/code&gt;
selects some of the \(N!\) permutations with higher probability than
others and isn’t uniform.&lt;/p&gt;
&lt;/details&gt;

&lt;h3 id=&quot;floyds-algorithm&quot;&gt;Floyd’s algorithm&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;What is optimal?&lt;/strong&gt; In a sense, the partial shuffle/swapping-based
solution is optimal – it’s \(O(k)\) with minimal space overhead. Its
only imperfection is the
fact that the input array &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;L&lt;/code&gt; is modified. Of course this can be
avoided by making a copy, but that means we are no longer \(O(k)\).&lt;/p&gt;

&lt;p&gt;Can we avoid modifying the input? No simple change to the
swapping-based solution will achieve that, because the algorithm uses
the buffer as a scratchpad to keep track of which of the \(N!\)
permutations has been selected.&lt;/p&gt;

&lt;p&gt;An \(O(k)\) &lt;em&gt;space and time&lt;/em&gt; solution to this exercise could dispense
with the array altogether, since it really just selects \(k\)
indices. One could simply ask:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Generate &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;k&lt;/code&gt; distinct uniformly random integers in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;range(N)&lt;/code&gt; in
\(O(k)\) space and time.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;I had asked many candidates the sampling question before I found
this version, innocently stated as &lt;a href=&quot;https://archive.org/details/pdfy-MgN0H1joIoDVoIC7/page/n123/mode/2up&quot;&gt;Exercise 5-2 of the AWK
programming
book&lt;/a&gt;. Their
&lt;a href=&quot;https://archive.org/details/pdfy-MgN0H1joIoDVoIC7/page/n209/mode/2up&quot;&gt;proposed
solution&lt;/a&gt;,
translated to Python, reads like this:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;random&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;randrange&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;N&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;result&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;set&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;N&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;N&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# k steps.
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;r&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;randrange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;r&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;result&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;r&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;result&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;add&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;r&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;result&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This is known as &lt;em&gt;Floyd’s algorithm&lt;/em&gt;, due to R.W. Floyd, 1978 Turing
Award winner and close collaborator of Donald Knuth at Stanford.&lt;/p&gt;

&lt;p&gt;It wasn’t immediately obvious to me why this algorithm is correct. The
fact that the math of “if seen already, choose the end” works
is somewhat magical. For a discussion of Floyd’s algorithm,
check out &lt;a href=&quot;https://dl.acm.org/doi/10.1145/30401.315746&quot;&gt;“A Sample of Brilliance” in Jon Bentley’s &lt;em&gt;Programming
Pearls&lt;/em&gt;&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Very few people will be able to derive something like that
in the scope of a coding interview. Only a handful of people
even know this algorithm in the first place;
nobody I ever interviewed did.&lt;/p&gt;

&lt;h2 id=&quot;version-2-on-solutions&quot;&gt;Version 2: \(O(N)\) solutions&lt;/h2&gt;

&lt;p&gt;One of the neat properties of this problem is its many
variations. Having solved the original version, what if we look to
sample from a &lt;em&gt;stream&lt;/em&gt; instead? A stream is an object that we can ask
for its next value, which will either yield another value or tell us
the stream has ended. In Python, that maps to the concept of an
&lt;a href=&quot;https://docs.python.org/3/glossary.html#term-iterator&quot;&gt;iterator&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;For this exercise to make sense, we need some guarantees: The stream
needs to (1) have at least &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;k&lt;/code&gt; elements, and (2) eventually end.&lt;/p&gt;

&lt;p&gt;The point of asking about streams is to force the solution to be
\(O(N)\), which gives a different landscape of trade-offs. Of course,
we could simply collect all \(N\) items in an array and apply the
solutions we already saw, but perhaps we can do this in \(O(k)\) space?&lt;/p&gt;

&lt;h3 id=&quot;streams-of-known-length&quot;&gt;Streams of known length&lt;/h3&gt;

&lt;h4 id=&quot;selection-sampling&quot;&gt;Selection sampling&lt;/h4&gt;

&lt;p&gt;Let’s say we also get information about the eventual length of the
stream. In that case, sampling \(k\) out of the \(N\) items we will
see, naively, is&lt;sup id=&quot;fnref:random0&quot; role=&quot;doc-noteref&quot;&gt;&lt;a href=&quot;#fn:random0&quot; class=&quot;footnote&quot; rel=&quot;footnote&quot;&gt;3&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;random&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;it&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;N&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;e&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;it&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;N&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;yield&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;e&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The issue with this algorithm is that it could sample both fewer and
more than \(k\) elements. It’s correct “on average” but each run has
some variation.&lt;/p&gt;

&lt;p&gt;Sampling too much is easily fixable – we can just stop after \(k\)
samples. But it’s unclear if that maintains uniformity, and anyway
what can we do about sampling too little? What we should do is
to increase the probability as we go along, for instance in a situation
where we have sampled \(k - 1\) elements and the stream only contains
a single final element, that one has to be sampled with probability
\(1\).&lt;/p&gt;

&lt;p&gt;To achieve that, note that regardless of whether we chose to sample or
not to sample an element in a given round, we modified the problem by
reducing the size of the remaining stream by one, and if we sampled an
element we reduced the number of yet-to-be-sampled elements by one as
well. In a situation where only a single element is left to be sampled
and we need another sample, we have a \(k=1\), \(N=1\) subproblem. This
suggests the approach&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;random&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;it&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;N&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;e&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;it&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;N&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;yield&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;e&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;N&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Optionally, we could also short-circuit via something like &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;if not k:
return&lt;/code&gt;. A moment’s reflection shows that this algorithm always
produces \(k\) elements and is correct.&lt;/p&gt;

&lt;p&gt;This algorithm is Knuth’s Algorithm S, “selection sampling” (from &lt;em&gt;The
Art of Computer Programming&lt;/em&gt;, Vol. 2, §3.4.2). It is short, sweet, and
“online” – we can yield instead of waiting for the stream to finish.
It is the right approach for many applications, including handling
classic magnetic tapes which are linear by nature.&lt;/p&gt;

&lt;h3 id=&quot;streams-of-unknown-length&quot;&gt;Streams of unknown length&lt;/h3&gt;

&lt;p&gt;What should we do if we are not being given the length of the stream
in advance? What &lt;em&gt;can&lt;/em&gt; we do?&lt;/p&gt;

&lt;p&gt;One obvious thing we cannot do anymore is to have an online solution
that &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;yield&lt;/code&gt;s its results. Since the stream could go on for many more
elements or stop right now and each element needs to have the same
chance of making it, any solution will have to have the form&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;it&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;results&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;e&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;it&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# do things and add to results
&lt;/span&gt;        &lt;span class=&quot;p&quot;&gt;...&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;results&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;heaps&quot;&gt;Heaps&lt;/h4&gt;

&lt;p&gt;One first idea might be to sort random numbers. We could for instance
maintain a min-heap, along the following lines:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;heapq&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;random&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;it&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;next&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;it&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;heapq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;heapify&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Tuples compare by first value first.
&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;e&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;it&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Push e on heap, then pop smallest.
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;heapq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;heappushpop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;e&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;e&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;e&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Somewhat surprisingly, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;heapify&lt;/code&gt; is implementable in \(O(k)\). The use
of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;heappushpop&lt;/code&gt; here makes sense since heap operations are typically
“modify the heap as requested, then recreate the heap property”. Since
here each push is followed by a pop, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;heappushpop&lt;/code&gt; allows us to skip
one heap recreation. It runs in \(O(\log k)\) for a heap of size
\(k\).&lt;/p&gt;

&lt;p&gt;Overall this algorithm is \(O(k) + O(N \log k)\) in time.&lt;/p&gt;

&lt;p&gt;There is an issue with this approach though: It relies on each
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;random()&lt;/code&gt; number being truly different from each other one. Since
Python’s &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float&lt;/code&gt;s don’t have infinite precision, collisions
are possible and due to the birthday paradox are actually
more likely than intuitively expected.&lt;sup id=&quot;fnref:birthday&quot; role=&quot;doc-noteref&quot;&gt;&lt;a href=&quot;#fn:birthday&quot; class=&quot;footnote&quot; rel=&quot;footnote&quot;&gt;4&lt;/a&gt;&lt;/sup&gt; If our streamed
elements are not comparable, this will make the above algorithm crash
at runtime – and if they are, uniformity will be violated. The
only real solution to this I can see is to modify the comparison to
have random tie breaks which breaks the deterministic runtime behavior
and is not pleasant to implement.&lt;/p&gt;

&lt;h4 id=&quot;quickselect&quot;&gt;Quickselect&lt;/h4&gt;

&lt;p&gt;While it doesn’t apply in the streaming case, it’s good to remember
that quickselect is the standard algorithm for finding the \(k\)th
smallest element in an unsorted list, or the \(k\) smallest
elements. However since it requires modifying the full array, it isn’t
the best approach for the problem at hand. (It also suffers from the
same floating point collision issue.) It’s still very good to know
quickselect, which is why I mention it here.&lt;/p&gt;

&lt;h4 id=&quot;reservoir-sampling&quot;&gt;Reservoir sampling&lt;/h4&gt;

&lt;p&gt;The real beauty of the streaming version of this question comes out in
this solution. Let’s go back to the template we know we will require:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;it&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;results&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;e&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;it&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# do things and add to results
&lt;/span&gt;        &lt;span class=&quot;p&quot;&gt;...&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;results&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;We can view this question in several ways. One of them is to think of
it as some sort of adversarial game: Let’s say you are the algorithm
and the interviewer is the stream. The algorithm can do whatever it
wants with its inputs, but the stream can decide to either give
another element or end itself and ask you to “show your work” in the
least convenient moment possible.&lt;/p&gt;

&lt;p&gt;Thinking along these lines creates one realization: We have to be
correct for all kinds of values of \(N\) and \(k\), including \(N =
k\). In that case there isn’t much we can do, we need to return the
first \(k\) inputs. So let’s code that:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;it&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;results&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;next&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;it&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;e&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;it&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# do things and add to results
&lt;/span&gt;        &lt;span class=&quot;p&quot;&gt;...&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;results&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This now is at least correct for the \(N = k\) case. Can we make it
correct for \(N = k + 1\) as well? (You see where this is going.) For
\(N = k + 1\), what’s the chance of any given element to be in the
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;results&lt;/code&gt; array? It will be \(\frac{k}{k+1}\). Essentially, &lt;em&gt;if&lt;/em&gt; we
see another element after the guaranteed first \(k\), what
choice do we have? We can choose it or reject it with a certain
probability, and if we choose it, we can evict a previously chosen
element with some probability. Since the stream could end right after
that additional element, &lt;em&gt;its&lt;/em&gt; probability of being chosen has to be
correct, namely &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;k / N&lt;/code&gt; which is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;k / stream_len_so_far&lt;/code&gt; in this case.&lt;/p&gt;

&lt;p&gt;This is the beauty of this algorithm: We have to &lt;em&gt;assume&lt;/em&gt; a solution
can be found, and under that assumption we only have that choice:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;random&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;it&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;results&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;next&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;it&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stream_len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;e&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;it&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Start with k + 1
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stream_len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Choose `e`.
&lt;/span&gt;            &lt;span class=&quot;p&quot;&gt;...&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;results&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This is almost the full algorithm. The remaining question is what to
evict? Given the uniform sample we want to produce, it stands to
reason that we want to select elements for eviction from the pool
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;results&lt;/code&gt; – let’s actually call it a reservoir – with
uniform probability:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;random&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;randrange&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;it&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;reservoir&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;next&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;it&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stream_len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;e&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;it&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stream_len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;reservoir&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;randrange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;e&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;reservoir&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;A slight optimization requires only a single random choice here:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;random&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;randrange&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;it&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;reservoir&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;next&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;it&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stream_len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;e&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;it&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;randrange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stream_len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;reservoir&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;e&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;reservoir&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;That is a neat algorithm. But is it correct? We arrived at it by
assuming something like this is possible; in particular, we chose the
probabilities such that the final element’s chance of ending in the
chosen set is correct.&lt;/p&gt;

&lt;p&gt;Given enough time, good candidates arrive at a short inductive proof of the
correctness of this algorithm. For a given \(k\), the probability for
any element to end up in the final set is obviously correct if \(N =
k\). Assuming the algorithm is correct for a given stream length
\(N\), moving to a stream length \(N + 1\) requires one more
iteration. We already know the final new element is chosen with the
right probability, but what happens to the other elements? Their
previous chance to end up in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;reservoir&lt;/code&gt; was \(k / N\). Their chance
to still be in the reservoir after one more iteration is &lt;em&gt;that&lt;/em&gt;, times (1) the
chance of the final element to be discarded, plus (2) the chance of
the final element to be chosen, but another element to be
evicted. This telescopes nicely since&lt;/p&gt;

\[\frac{k}{N} \cdot \Big(1 - \frac{k}{N+1} + \frac{k}{N+1} \cdot \frac{k-1}{k}\Big)
= \frac{k}{N} \cdot \Big(\frac{N + 1 - k}{N + 1} + \frac{k - 1}{N +
1}\Big)
= \frac{k}{N} \cdot \frac{N}{N+1} = \frac{k}{N+1}.\]

&lt;p&gt;So the probabilities of the previous elements are updated in the
correct way too.&lt;/p&gt;

&lt;p&gt;This algorithm is known as &lt;em&gt;reservoir sampling&lt;/em&gt;. It’s a classic
from the literature; Knuth calls it Algorithm R in TAOCP Volume 2.&lt;/p&gt;

&lt;h4 id=&quot;reservoir-sampling-with-skipping-ahead&quot;&gt;Reservoir sampling with skipping ahead&lt;/h4&gt;

&lt;p&gt;Fancier versions of reservoir sampling exist. One
interesting variant is if we assume we can cheaply skip ahead in the
iterator. If the length of the stream &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;N&lt;/code&gt; is large compared to the
number of selected elements and there is processing work for each
element that pays off to be avoided where possible, this can be a
powerful idea.&lt;/p&gt;

&lt;p&gt;Let’s invent an iterator method where say &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;skip(it, j)&lt;/code&gt; skips and
discards &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;j&lt;/code&gt; elements from the iterator (making &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;skip(it, 0)&lt;/code&gt; a
no-op). The skipping version of reservoir sampling can then be written
as&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;math&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;floor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;log1p&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;random&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;randrange&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;it&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;done&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;object&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;reservoir&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;next&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;it&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;skip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;it&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;floor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;log1p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;e&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;next&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;it&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;done&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;done&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;reservoir&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;randrange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;e&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;reservoir&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Here &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;w&lt;/code&gt; is the probability that the next element of the stream will
be accepted, and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log1p(-w)&lt;/code&gt; computes \(\log(1 - w)\) without losing
precision when &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;w&lt;/code&gt; is small.&lt;sup id=&quot;fnref:logzero&quot; role=&quot;doc-noteref&quot;&gt;&lt;a href=&quot;#fn:logzero&quot; class=&quot;footnote&quot; rel=&quot;footnote&quot;&gt;5&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;

&lt;p&gt;This version of reservoir sampling was published in 1994 by Kim-Hung
Li, see &lt;a href=&quot;https://dl.acm.org/doi/10.1145/198429.198435&quot;&gt;Reservoir-sampling algorithms of time complexity \(O(n(1 +
\log(N/n)))\)&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;There are other interesting variants of reservoir sampling, e.g.,
sampling from non-uniform distributions. But let’s end with something
a bit farther afield that deserves to be better known.&lt;/p&gt;

&lt;h2 id=&quot;online-shuffling&quot;&gt;Online shuffling&lt;/h2&gt;

&lt;p&gt;Let’s say we have a large dataset (e.g., a table in SQL)
which comes in the form&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;  # |   value
-------------
  1 |  entry1
  . | .
  . | .
  . | .
  N |  entryN
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;We now want to do “online shuffling”, i.e., go through the dataset in
a random order, visiting each sample exactly once. We also want to be
preemptible – our algorithm can be stopped and later restarted from a
checkpoint. Perhaps we would even like this to be &lt;em&gt;seekable&lt;/em&gt;: Quickly
asking for the entry that comes at position &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;i&lt;/code&gt; of the shuffle.&lt;/p&gt;

&lt;p&gt;What we are asking for is equivalent to selecting one of the \(N!\)
many permutations of \(N\) items, then doing lookups of the form&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;N&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;sample&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;...&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This is similar to the sampling question in that doing this requires a
scratch buffer of size \(O(N)\) to keep track of what has been sampled so
far. For instance, this could be done like:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;random&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;randrange&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;permit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;N&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;arange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;N&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;N&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;randrange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;N&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;yield&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;However, this is a heavy amount of state for our checkpoint: For a
dataset of 1B entries we would use 8 GiB just for the
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.arange(N)&lt;/code&gt;. It’s also not quickly seekable in that the full array
needs to be assembled before we can do lookups.&lt;/p&gt;

&lt;h3 id=&quot;block-ciphers&quot;&gt;Block ciphers&lt;/h3&gt;

&lt;p&gt;If we want to deal with far less state (say, a few kilobytes), the
problem cannot be solved &lt;em&gt;exactly&lt;/em&gt;. But it can be
solved approximately, and one can prove the approximation is good.&lt;/p&gt;

&lt;p&gt;One trick is to use an idea from cryptography: A &lt;em&gt;block cipher&lt;/em&gt; is a
symmetric encryption algorithm which takes a secret key &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;k&lt;/code&gt; and buffers of
a fixed length and maps them to encrypted buffers of the same length:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;plain text buffer: B
encrypted buffer:  encrypt(B, k)
decrypted buffer:  B == decrypt(encrypt(B, k), k)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Both the unencrypted input &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;B&lt;/code&gt; and the encrypted buffer &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;encrypt(B, k)&lt;/code&gt;
have the same number of bits, say \(n\). In particular, this means
that for a given key &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;k&lt;/code&gt; the functions&lt;/p&gt;

\[\begin{align}
\mathtt{encrypt}(\dotid, \mathtt{k}) &amp;amp; \from \set{0, 1}^{n} \to \set{0,
1}^{n}, \\
\mathtt{decrypt}(\dotid, \mathtt{k}) &amp;amp; \from \set{0, 1}^{n} \to \set{0,
1}^{n}
\end{align}\]

&lt;p&gt;are bijections (one-to-one) and each is the inverse of the
other. Here, \(\set{0, 1}^{n}\) is the set of all buffers of 0s and 1s
of length \(n\), which is a set of \(2^n\) elements.&lt;/p&gt;

&lt;h3 id=&quot;pseudorandom-permutations&quot;&gt;Pseudorandom permutations&lt;/h3&gt;

&lt;p&gt;How are we going to use this block cipher? We will use \(n = 64\) and
interpret a given index &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;i&lt;/code&gt; of type &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;uint64&lt;/code&gt; as a block of 64 bits and
use a block cipher for that block size. We then encrypt that index to
find where it maps to:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;perm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;uint64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;KEY&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Global in this example.
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;encrypt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;permit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;N&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;N&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;yield&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;perm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Since \(\mathtt{encrypt}(\dotid, \mathtt{k})\) is one-to-one, each
possible bit pattern is produced exactly once. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;perm&lt;/code&gt; is an actual
permutation of the set of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;uint64&lt;/code&gt;s (a set of \(2^{64}\) elements).&lt;/p&gt;

&lt;p&gt;This works as described if the (implausibly large) table has size
exactly \(N = 2^n = 2^{64}\). Realistically, it’s smaller and we need
some additional ideas.&lt;/p&gt;

&lt;p&gt;Let’s say we have a block cipher for any power of two and a table of
any size. We can use as block size \(n\) the smallest number such that
\(2^n \ge\) the table size. Worst case, this additional
padding at the end is roughly half the range of the permutation. When
we apply &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;perm&lt;/code&gt; and hit the padded region, we will simply iterate
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;perm&lt;/code&gt; until we get out of it – since the permutation is one-to-one,
that will eventually happen, and since the padded part is at most
half, it happens with probability at least 0.5 every iteration. This
trick is known as &lt;em&gt;cycle walking&lt;/em&gt;.&lt;/p&gt;

&lt;h3 id=&quot;is-0-enough&quot;&gt;Is 0% enough?&lt;/h3&gt;

&lt;p&gt;Note that the permutation is parameterized only by the key &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;k&lt;/code&gt;. If &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;k&lt;/code&gt;
has &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;m&lt;/code&gt; bits, that means we can only produce \(2^m\) different
permutations, which is vastly fewer than the full number of
permutations of the set of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;uint64&lt;/code&gt;s, which is \((2^{64})!\), a number
that has about \(3.47 \times 10^{20}\) digits. By contrast,
the number of atoms in the observable universe has about 80 digits!
Combinatorics creates large numbers very fast.&lt;sup id=&quot;fnref:digits&quot; role=&quot;doc-noteref&quot;&gt;&lt;a href=&quot;#fn:digits&quot; class=&quot;footnote&quot; rel=&quot;footnote&quot;&gt;6&lt;/a&gt;&lt;/sup&gt; The actual fraction of
permutations reachable by this scheme is very close to \(0\%\).&lt;/p&gt;

&lt;p&gt;So we will only ever get an absurdly tiny fraction of all possible
permutations this way. How far away from truly random permutations
are we with these &lt;em&gt;pseudorandom permutations&lt;/em&gt;?&lt;/p&gt;

&lt;p&gt;The answer depends on the quality of the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;encrypt&lt;/code&gt; function. In many
scenarios, cryptographers could prove that one cannot actually tell
the difference! To learn more, check out &lt;a href=&quot;https://en.wikipedia.org/wiki/Feistel_cipher&quot;&gt;Feistel
networks&lt;/a&gt;&lt;sup id=&quot;fnref:feistel&quot; role=&quot;doc-noteref&quot;&gt;&lt;a href=&quot;#fn:feistel&quot; class=&quot;footnote&quot; rel=&quot;footnote&quot;&gt;7&lt;/a&gt;&lt;/sup&gt; and a
result known as the &lt;em&gt;Luby-Rackoff theorem&lt;/em&gt;.&lt;sup id=&quot;fnref:lubyrackoff&quot; role=&quot;doc-noteref&quot;&gt;&lt;a href=&quot;#fn:lubyrackoff&quot; class=&quot;footnote&quot; rel=&quot;footnote&quot;&gt;8&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;

&lt;h3 id=&quot;cheap-parameterized-permutations&quot;&gt;Cheap parameterized permutations&lt;/h3&gt;

&lt;p&gt;On the other end of the spectrum, computationally cheap parameterized permutations
come from &lt;em&gt;mixers&lt;/em&gt; (or &lt;em&gt;finalizers&lt;/em&gt;) of hash functions like
MurmurHash3. A &lt;a href=&quot;https://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html&quot;&gt;very influential 2011 blog post by David
Stafford&lt;/a&gt;
proposed using&lt;/p&gt;

&lt;div class=&quot;language-c highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;uint64_t&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;mix13&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;uint64_t&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;^=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*=&lt;/span&gt; &lt;span class=&quot;mh&quot;&gt;0xBF58476D1CE4E5B9UL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;^=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;27&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*=&lt;/span&gt; &lt;span class=&quot;mh&quot;&gt;0x94D049BB133111EBUL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;^=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;31&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;MurmurHash3 and this blog post were the starting point of all kinds of
results around fast permutations. Stafford’s suggestion made it into
&lt;a href=&quot;https://github.com/openjdk/jdk/commit/231a351a47d4d3fb8034115584bef6847486bc68&quot;&gt;JDK 8 in
2013&lt;/a&gt;
and was also cited as canonical in &lt;em&gt;Fast Splittable
Pseudorandom Number Generators&lt;/em&gt; by Steele, Lea and Flood
in 2014. Since 2018, Pelle Evensen has had
&lt;a href=&quot;http://mostlymangling.blogspot.com/2018/07/on-mixing-functions-in-fast-splittable.html&quot;&gt;several&lt;/a&gt;
&lt;a href=&quot;http://mostlymangling.blogspot.com/2020/01/nasam-not-another-strange-acronym-mixer.html&quot;&gt;blog
posts&lt;/a&gt;
around improvements. These fast permutations satisfy certain
statistical properties but not others (e.g., &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mix13&lt;/code&gt; above sends an
all zero buffer to zero; this can be fixed with extra xors). They are
certainly not “cryptographically strong”, but their statistical
properties can be surprisingly good and they are extremely cheap.&lt;/p&gt;

&lt;p&gt;Much more can be said about random sampling and shuffling. But this blog
post is long enough and making it longer will not illustrate the point
any better.&lt;/p&gt;
&lt;div class=&quot;footnotes&quot; role=&quot;doc-endnotes&quot;&gt;
  &lt;ol&gt;
    &lt;li id=&quot;fn:randrange&quot; role=&quot;doc-endnote&quot;&gt;
      &lt;p&gt;The Python standard library also has a
&lt;tt&gt;random.randrange(start, stop[, step])&lt;/tt&gt; version, but we
will use the one-argument version of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;randrange&lt;/code&gt; here. &lt;a href=&quot;#fnref:randrange&quot; class=&quot;reversefootnote&quot; role=&quot;doc-backlink&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
    &lt;li id=&quot;fn:style&quot; role=&quot;doc-endnote&quot;&gt;
      &lt;p&gt;Yes, we’ll be using &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;L&lt;/code&gt; as a Python variable name,
regardless of what the &lt;a href=&quot;https://google.github.io/styleguide/pyguide.html&quot;&gt;Google Python Style
Guide&lt;/a&gt; says. One
of the advantages of leaving Google is to be &lt;em&gt;free&lt;/em&gt;. &lt;a href=&quot;#fnref:style&quot; class=&quot;reversefootnote&quot; role=&quot;doc-backlink&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
    &lt;li id=&quot;fn:random0&quot; role=&quot;doc-endnote&quot;&gt;
      &lt;p&gt;Note that &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;random() &amp;lt; k/N&lt;/code&gt; with a strict &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt;&lt;/code&gt; (and not
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt;=&lt;/code&gt;) is the correct comparison; this matches the property where
the return value of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;random()&lt;/code&gt; &lt;em&gt;can&lt;/em&gt; be &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.0&lt;/code&gt; but can not be
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1.0&lt;/code&gt;. &lt;a href=&quot;#fnref:random0&quot; class=&quot;reversefootnote&quot; role=&quot;doc-backlink&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
    &lt;li id=&quot;fn:birthday&quot; role=&quot;doc-endnote&quot;&gt;
      &lt;p&gt;On a typical contemporary computer, a Python &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float&lt;/code&gt; is
a double aka &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float64&lt;/code&gt;. Python’s &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;random()&lt;/code&gt; returns one of \(N =
2^{53}\) equally spaced doubles in \([0,
1)\). The birthday threshold is \(\sqrt{2N\ln 2}\) which is around
111M. But for the heap solution we have to worry about collisions
at the selection boundary, which are very unlikely for realistic
stream lengths. &lt;a href=&quot;#fnref:birthday&quot; class=&quot;reversefootnote&quot; role=&quot;doc-backlink&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
    &lt;li id=&quot;fn:logzero&quot; role=&quot;doc-endnote&quot;&gt;
      &lt;p&gt;Funnily enough, the code isn’t quite bug-free as
written. Since &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;random()&lt;/code&gt; can be &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.0&lt;/code&gt;,
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;math.log(random())&lt;/code&gt; can raise a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ValueError&lt;/code&gt; with probability
\(2^{-53}\). A full implementation should probably special-case
both &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;w == 0.0&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;w == 1.0&lt;/code&gt;. &lt;a href=&quot;#fnref:logzero&quot; class=&quot;reversefootnote&quot; role=&quot;doc-backlink&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
    &lt;li id=&quot;fn:digits&quot; role=&quot;doc-endnote&quot;&gt;
      &lt;p&gt;How do I know the digits of \((2^{64})!\)? It turns out the Log-gamma
function \(\ln\circ\,\Gamma\) is a well understood object with a
fast converging series representation. Since \(\Gamma(n + 1) =
n!\), we can literally compute
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;math.lgamma(2**64 + 1)&lt;/code&gt; and convert \(\ln\) to \(\log_{10}\). &lt;a href=&quot;#fnref:digits&quot; class=&quot;reversefootnote&quot; role=&quot;doc-backlink&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
    &lt;li id=&quot;fn:feistel&quot; role=&quot;doc-endnote&quot;&gt;
      &lt;p&gt;The tl;dr on Feistel networks is: Split the input into its
left and right part, then compute &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;right, left = left ^
hash(right, key), right&lt;/code&gt; for a number of rounds. Decryption is
doing the same kind of operation in reverse. &lt;a href=&quot;#fnref:feistel&quot; class=&quot;reversefootnote&quot; role=&quot;doc-backlink&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
    &lt;li id=&quot;fn:lubyrackoff&quot; role=&quot;doc-endnote&quot;&gt;
      &lt;p&gt;Note though that the specific mathematical guarantee from
Luby-Rackoff does not map well to a large table that we shuffle
completely since the bound is \(q^2 / 2^{n/2}\) after \(q\)
queries. For \(n=64\) this is exhausted after \(q\approx 2^{16} =
65536\) queries. For better mathematical guarantees, unbalanced
Feistel ciphers can help, as can modern schemes like
&lt;a href=&quot;https://www.cs.ucdavis.edu/~rogaway/papers/shuffle.html&quot;&gt;swap-or-not&lt;/a&gt;,
which survives for \(q\) close to \(2^n\). Alternatively,
one can use ciphers like
&lt;a href=&quot;https://en.wikipedia.org/wiki/Speck_(cipher)&quot;&gt;Speck&lt;/a&gt;, which
have no formal guarantee but are deemed secure because no
successful attack is publicly known (but people
tried). Note though that for practical table sizes one
would need something unofficial like Speck40 to get the right
block size, which is likely just as good but has had fewer eyes on it. &lt;a href=&quot;#fnref:lubyrackoff&quot; class=&quot;reversefootnote&quot; role=&quot;doc-backlink&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
  &lt;/ol&gt;
&lt;/div&gt;
</description>
        <pubDate>Tue, 18 Aug 2026 00:00:00 +0000</pubDate>
        <link>https://heiner.ai/blog/2026/08/18/random-samples.html</link>
        <guid isPermaLink="true">https://heiner.ai/blog/2026/08/18/random-samples.html</guid>
        
        
        <category>blog</category>
        
      </item>
    
      <item>
        <title>A Leetcode-style interviewer&apos;s apology</title>
        <description>&lt;p&gt;People love to hate leetcode-style interviews. On X, they are
regularly described as a waste of time for all parties
involved. People point out that real programming jobs are nothing like
these artificial 30-60 minute situations, that software engineers can
have decade-long careers without ever implementing the algorithms that
are regularly discussed during these interviews, and that AI means
encyclopedic knowledge of algorithms is even more useless than it
was before.&lt;sup id=&quot;fnref:failure&quot; role=&quot;doc-noteref&quot;&gt;&lt;a href=&quot;#fn:failure&quot; class=&quot;footnote&quot; rel=&quot;footnote&quot;&gt;1&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;

&lt;p&gt;Some of that is true. And yet, the critics of leetcode-style
interviews are mistaken. When faced with the &lt;em&gt;practical&lt;/em&gt; question of
assessing within minutes whether a given candidate would be a useful
co-worker, leetcode-style questions are hard to beat.&lt;/p&gt;

&lt;p&gt;Why is that? I don’t think there is a single mechanism.
It’s easy to criticize leetcode-style questions since they assess a
combination of skills and desiderata but don’t nail any single
one. Let’s therefore describe what leetcode interviews &lt;em&gt;do&lt;/em&gt; assess and
why that’s a good thing. To make matters more concrete, I’ll describe
one of my favorite leetcode-style interview questions in the &lt;a href=&quot;/blog/2026/08/18/random-samples.html&quot;&gt;next
blog post&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Leetcode-style questions test if you can code.&lt;/strong&gt; It’s stupid, but a
good fraction of candidates will &lt;a href=&quot;https://blog.codinghorror.com/why-cant-programmers-program/&quot;&gt;fail even
FizzBuzz&lt;/a&gt;. They
just cannot code. &lt;em&gt;Any&lt;/em&gt; interview that involves coding will find that;
having a rule that says a specific interview is for coding exclusively
helps get to fast failure for hopeless cases.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Leetcode-style questions can be prepared for.&lt;/strong&gt; That is the
very business model of &lt;a href=&quot;https://leetcode.com&quot;&gt;leetcode.com&lt;/a&gt;. Becoming
good at these kinds of questions takes a lot of work. Combined with the
supposed uselessness of the skill thereby acquired, this is used as an
argument against them. But not so: One of the practical questions an
interviewer has to answer is just how excited a given candidate is
about the job, and about the occupation of programming for a living in
the first place. Putting in weeks, or months, of prep time is a strong
signal that the candidate is &lt;em&gt;interested in software&lt;/em&gt;. That is a lot!
In fact, the best programmers I know are &lt;em&gt;excited&lt;/em&gt; to discuss new
little questions, not too different from how mathematicians discuss
little exercises. Being interested in how to find unique triplets of
array entries that sum to zero correlates with just being interested
in computers and how they work. Sitting down and preparing for a job
interview means being at least somewhat interested in the job and the
company. That alone eliminates a large fraction of weak
candidates. On top of that, companies seek employees who are willing
and able to work hard on something. Leetcode graduates proved they
can.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Leetcode-style questions test intelligence.&lt;/strong&gt; While candidates
sometimes try to brute-force these questions by remembering all
possible answers, people with high IQ have a huge natural
advantage. Smart people are generally useful, and assessing &lt;em&gt;how
smart a candidate is&lt;/em&gt; is a core part of interviews (being smart covers
a multitude of other flaws). That is also why universities find SAT
results useful. Of course, measuring IQ directly via a test would
presumably be more precise, but the US has a history of
disincentivizing this since the outcomes are politically disfavored. And a
pure IQ test would likely be less meaningful since leetcode-style
questions cover more ground, including prior knowledge:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Leetcode-style questions test knowledge.&lt;/strong&gt;
The contrast between rote memorization and skill is
not as strict as it’s sometimes made out to be, neither in software
engineering nor in other areas such as math. Knowing what, e.g., a Bloom
filter is is genuinely useful, as is knowing the name of the thing. Since
practically nobody is able to re-derive meaningful parts of computer
science from scratch by themselves (there is &lt;em&gt;some&lt;/em&gt; content to the
field after all), knowing what
exists and how to talk about it is a useful skill. During the actual
work of a good software engineer, various design decisions and
judgment calls about systems have to be made. Knowing the toolbox, and
knowing it well, is essential to making these decisions well. This can
be traded off with intelligence or other sources of good intuition
about these practical problems, but ceteris paribus knowing more is
better.&lt;/p&gt;

&lt;p&gt;Of course that depends on the type of software engineering role the
candidate wants to fill. Folks writing database lookups for a Django
app may not need to know Fenwick trees. However, that brings me to&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;AI’s impact on software engineering.&lt;/strong&gt; I cannot foresee all
consequences of coding models on the ecosystem but it seems likely it
will change a lot and fast. It’s possible the role won’t
exist at all in the near term, in which case all interview techniques
are obsolete. It stands to reason though that the more routine, more
obviously automatable tasks will be automated first. Who’s got
more job security, the guy who knows about Zobrist hashing or the
hundredth CRUD engineer? I don’t know if “be the knowledgeable engineer”
is actionable advice – since nobody decided to be somewhat
disinterested, most people just are like that – but “hire the
knowledgeable engineer” is. Knowledgeable engineers work on harder, more interesting
problems and are likely to at some point in their career engage with
“low-level fundamentals”. The blunt answer to the “I’ve never needed
this” argument is &lt;a href=&quot;https://www.smbc-comics.com/comic/why-i-couldn39t-be-a-math-teacher&quot;&gt;“but the good ones
do”&lt;/a&gt;. And
for what it’s worth, several of the ideas described in the &lt;a href=&quot;/blog/2026/08/18/random-samples.html&quot;&gt;next
post&lt;/a&gt; did end up being
relevant in my career.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Leetcode-style questions are an industry standard for a reason.&lt;/strong&gt;
The artificialness of asking a problem from a predefined pool, again
and again and again, is even more obvious to the interviewers than it
is to the critics. Trying to do something smarter is a decades-old
idea. In his 2015 book, the long-time Google head of recruitment
Laszlo Bock described some of the ideas of early Google. They include
nifty ideas like programming-related easter eggs in Google search and
McKinsey-style brainteasers. Few if any of the cool ideas worked, and
Google instead relied on ~four structured interviews from a shared pool
with defined rubrics.&lt;sup id=&quot;fnref:google&quot; role=&quot;doc-noteref&quot;&gt;&lt;a href=&quot;#fn:google&quot; class=&quot;footnote&quot; rel=&quot;footnote&quot;&gt;2&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Leetcode-style questions are &lt;em&gt;doable&lt;/em&gt;.&lt;/strong&gt; Is passing a leetcode-style
interview the best possible signal a candidate can have? Far from
it. Meaningful previous projects are better by far. Being able to talk
in detail about related work is better. Being Linus Torvalds is
better. But as hard as preparing for coding interviews is, producing
&lt;em&gt;those&lt;/em&gt; signals is harder still for most candidates, especially the
youngest and least well-connected. Companies don’t have the resources
to give most candidates an internship, but they can and will interview
the promising ones.&lt;/p&gt;

&lt;p&gt;This is not to say that all leetcode-style interviews are done
well. To give a bit of flavor as to what kinds of questions I like to
ask, &lt;a href=&quot;/blog/2026/08/18/random-samples.html&quot;&gt;read about my favorite interview question in part two&lt;/a&gt;.&lt;/p&gt;
&lt;div class=&quot;footnotes&quot; role=&quot;doc-endnotes&quot;&gt;
  &lt;ol&gt;
    &lt;li id=&quot;fn:failure&quot; role=&quot;doc-endnote&quot;&gt;
      &lt;p&gt;Another reason some people dislike leetcode-style
questions is that they experienced them and did not end up getting
an offer. That happened to me too – when I first applied to Google
in Munich after my math PhD, I was woefully underprepared and no
match for the L4 coding interviews (which were on the tough end,
one of them was asking to implement a parallel regex matching
engine). Leetcode-style questions certainly are not perfect and
end up having false negatives. However, precision is &lt;em&gt;much more&lt;/em&gt;
important when hiring than recall is. That is true even though
getting rejected for a position one would have excelled in is sad. &lt;a href=&quot;#fnref:failure&quot; class=&quot;reversefootnote&quot; role=&quot;doc-backlink&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
    &lt;li id=&quot;fn:google&quot; role=&quot;doc-endnote&quot;&gt;
      &lt;p&gt;This was when Google was cool. &lt;a href=&quot;#fnref:google&quot; class=&quot;reversefootnote&quot; role=&quot;doc-backlink&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
  &lt;/ol&gt;
&lt;/div&gt;
</description>
        <pubDate>Tue, 18 Aug 2026 00:00:00 +0000</pubDate>
        <link>https://heiner.ai/blog/2026/08/18/leetcode.html</link>
        <guid isPermaLink="true">https://heiner.ai/blog/2026/08/18/leetcode.html</guid>
        
        
        <category>blog</category>
        
      </item>
    
      <item>
        <title>Some specific integrals</title>
        <description>
&lt;div class=&quot;right&quot;&gt;
  &lt;p&gt;&lt;cite&gt;“Aber dann können sie’s!”&lt;/cite&gt; &lt;br /&gt;&lt;/p&gt;
&lt;/div&gt;

&lt;p&gt;Two decades ago I was a math undergrad in Dresden, Germany.&lt;/p&gt;

&lt;p&gt;At some point in the &lt;em&gt;Analysis I&lt;/em&gt; course they taught us about
solving integrals with the usual tricks: Integration by parts, substitution,
partial fractions. Unlike physics or some engineering undergrads, math
students would only see one or two examples and move on. I still
remember my undergrad instructor Gerd Kayser telling us how this
wasn’t proper training and how when he was a student, math undergrads
in socialist East Germany had to do a preparatory course where they
“had to solve 50 integrals”.&lt;/p&gt;

&lt;p&gt;“50 integrals is a lot”, he said, “but we were told we shouldn’t
complain since students in the Soviet Union have to solve 500. But
afterwards they know how to solve integrals!”&lt;/p&gt;

&lt;p&gt;The grace of my relatively late birth spared me having to do anywhere
close that many and I never got good at it. The art of detecting if
\(\tan\frac\theta 2\) is the right substitution continues to be lost
on me.&lt;/p&gt;

&lt;p&gt;In fact I was so bad at that sort of problem that my smart friends
gave me a personalized set of integration exercises a few years later:&lt;/p&gt;

&lt;div class=&quot;centered&quot;&gt;
  &lt;p&gt;&lt;a href=&quot;/img/integrale_page1.jpeg&quot; target=&quot;_blank&quot;&gt;&lt;img src=&quot;/img/integrale_page1.jpeg&quot; alt=&quot;42 integrals&quot; style=&quot;width:200px;&quot; /&gt;&lt;/a&gt;
&lt;a href=&quot;/img/integrale_page2.jpeg&quot; target=&quot;_blank&quot;&gt;&lt;img src=&quot;/img/integrale_page2.jpeg&quot; alt=&quot;42 integrals&quot; style=&quot;width:200px;&quot; /&gt;&lt;/a&gt;
&lt;a href=&quot;/img/integrale_page3.jpeg&quot; target=&quot;_blank&quot;&gt;&lt;img src=&quot;/img/integrale_page3.jpeg&quot; alt=&quot;42 integrals&quot; style=&quot;width:200px;&quot; /&gt;&lt;/a&gt;&lt;/p&gt;

  &lt;div class=&quot;centered small&quot;&gt;
    &lt;p&gt;42 integrals to solve. I still got until 2035!&lt;/p&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Lucky for me most of math isn’t about solving integrals. I eventually
got my diploma and moved on.&lt;/p&gt;

&lt;h2 id=&quot;explicit-but-tricky&quot;&gt;Explicit but tricky&lt;/h2&gt;

&lt;p&gt;Moved on to doing a PhD in Mathematical Physics, that is. The quantum
mechanical problem discussed in my thesis ultimately doesn’t
matter&lt;sup id=&quot;fnref:1&quot; role=&quot;doc-noteref&quot;&gt;&lt;a href=&quot;#fn:1&quot; class=&quot;footnote&quot; rel=&quot;footnote&quot;&gt;1&lt;/a&gt;&lt;/sup&gt; but it turned out that after applying a &lt;a href=&quot;https://en.wikipedia.org/wiki/Feynman_parametrization&quot;&gt;trick by
Feynman&lt;/a&gt;
to each term of a certain series I was left with,
ironically, an &lt;em&gt;explicit integral that required solving!&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Specifically, the \(n\)th term for \(n \ge 2\) produced the
\(n\)-dimensional integral&lt;/p&gt;

\[I_n := \int_{(0,\infty)^n} \frac{e^{-\sum_{j=1}^n u_j}} {\prod_{j=1}^{n-1} (u_j +
u_{j+1})}\d u\]

&lt;p&gt;where \((0,\infty)^n\) is the set of \(n\)-dimensional vectors
\(u\in\R^n\) with positive entries \(u_j &amp;gt; 0\).&lt;/p&gt;

&lt;p&gt;For small \(n\), I could solve this: \(I_2 = 1\), \(I_3 =
\frac{\pi^2}{6}\), and \(I_4 = \frac{\pi^2}{3}\). I could also do
numerics and find that \(I_5 \approx 7.3057 \approx \frac{3\pi^4}{40}\) and
\(I_6 \approx 17.3172\approx\frac{8\pi^4}{45}\). But the iterated
integrals turned complicated very quickly. Already for \(n=6\), the
identity \(I_6 = \frac{8\pi^4}{45}\) turns out to be equivalent to the
non-obvious dilogarithm integral&lt;/p&gt;

\[\int_0^1 \Bigl(\mathrm{Li}_2(\frac{x-1}{x})\Bigr)^2 \dx =
\frac{17}{180}\pi^4\]

&lt;p&gt;for the &lt;a href=&quot;https://en.wikipedia.org/wiki/Dilogarithm&quot;&gt;dilogarithm&lt;/a&gt;
\(\mathrm{Li}_2\). This is not exactly an obvious formula, although it
turned out to be implied by results in the literature, which confirmed
the value for \(n=6\).&lt;/p&gt;

&lt;h4 id=&quot;faith-in-math&quot;&gt;Faith in math&lt;/h4&gt;

&lt;p&gt;The numerical results gave me a conjecture. It looked like
\(I_{2n+2} = 2(2\pi)^{2n} \frac{(n!)^2}{(2n+2)!}\) might be correct.&lt;/p&gt;

&lt;p&gt;When I plugged this result into my series expansion, the right power
series coefficients (the one for \(\arcsin^2\))
would pop out and make the result of my thesis beautiful. The
conjecture &lt;em&gt;had&lt;/em&gt; to be true – the result was too good to be false!&lt;/p&gt;

&lt;p&gt;How to prove it though?&lt;/p&gt;

&lt;p&gt;I asked &lt;a href=&quot;https://mathoverflow.net/questions/129955/evaluation-of-an-n-dimensional-integral&quot;&gt;the
internet&lt;/a&gt;
but without receiving a super satisfactory result. However, after I massaged
the integral a bit my collaborator Peter Otte found a solution using
insights from operator theory, in particular Hankel operators.&lt;/p&gt;

&lt;p&gt;The integral for all \(n\) turned out to be implied by results
from the 1950s and earlier. To describe these, I have to go on a
slight tangent.&lt;/p&gt;

&lt;h4 id=&quot;an-integral-operator&quot;&gt;An integral operator&lt;/h4&gt;

&lt;p&gt;On \(L_2(0, \infty)\), i.e., the space of functions from the half-line \((0,
\infty)\) to the reals that are square-integrable, define an
operator \(L_2(0, \infty)
\ni f \mapsto Tf \in L_2(0,\infty)\), i.e., a mapping from functions
to functions, by&lt;/p&gt;

\[(Tf)(x) = \int_0^\infty \frac{e^{-(x+y)/2}}{x+y}f(y)\,\d y.\]

&lt;p&gt;This is an &lt;em&gt;integral operator&lt;/em&gt; of the form \((Tf)(x) = \int k(x, y) f(y)\,\d
y\). The function \(k(x, y)\) is called a &lt;em&gt;kernel&lt;/em&gt;. In this particular
case, the kernel depends on \(x+y\) only, not on
\(x\) and \(y\) separately. Such operators are known as &lt;em&gt;Hankel
operators&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;The reason the operator \(T\) is interesting vis-à-vis the integral
\(I_n\) is that applying it repeatedly yields iterated integrals that
look like \(I_n\). In fact,&lt;/p&gt;

\[I_n = \langle \varphi, T^{n-1} \varphi \rangle\]

&lt;p&gt;where \(\langle \dotid, \dotid\rangle\) is the scalar product on
\(L_2(0, \infty)\) and \(\varphi(x) := e^{-x/2}\).&lt;/p&gt;

&lt;p&gt;It turns out that the operator \(T\) has been studied by
mathematicians. Rosenblum (1958) gave an
explicit diagonalization of this operator. Diagonalization is
part of the spectral analysis of an operator, a powerful concept that
involves finding the fundamental properties of the operator as a
mathematical object (finding out all its secrets, as it were). Like
its finite-dimensional analog matrix diagonalization, it allows us to
compute “functions of the operator”, including its powers \(T^n\).&lt;/p&gt;

&lt;p&gt;The diagonalization of \(T\) due to Rosenblum can be written as
\begin{equation} \label{eq:Hilbert-matrix-unitary-relation}
  (UTf)(k) = \frac{\pi}{\cosh(k\pi)}(Uf)(k)  \where{k\in(0,\infty),
  f\in L_2(0,\infty)}
\end{equation}
for a specific unitary operator \(U\from L_2(0,\infty)\to
L_2(0,\infty)\). Unitary means that
\(U\) is a Hilbert space isomorphism, i.e. it maps the Hilbert space
\(L_2(0,\infty)\) to itself while leaving its structure in place; in
particular the scalar product of two mapped functions is the same as
the scalar product of the input functions. The operator
\(U\) can be explicitly computed although the details
are a bit messy and require a number of functions from the special
functions zoo (the Gamma function and the &lt;a href=&quot;https://dlmf.nist.gov/13.14&quot;&gt;Whittaker
functions&lt;/a&gt;). If you must know the details
you can check out chapter 8 of &lt;a href=&quot;https://edoc.ub.uni-muenchen.de/17442/&quot;&gt;my thesis&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Using these results, my integral expression can be turned into
something much more manageable, because with \(\hat{\varphi} :=
U\varphi\) one has&lt;/p&gt;

\[I_n = \langle \varphi, T^{n-1} \varphi \rangle
    = \langle U\varphi, UT^{n-1} \varphi \rangle
    = \int_0^\infty\d k\, \abs{\hat{\varphi}(k)}^2 \Big(\frac{\pi}{\cosh(k\pi)}\Big)^{n-1}\]

&lt;p&gt;by repeated application of Rosenblum’s diagonalization.&lt;/p&gt;

&lt;p&gt;The function \(\hat{\varphi}\) and the remaining one-dimensional
integral can be computed, and the result is&lt;/p&gt;

\[I_n = \frac{2}{n}(2\pi)^{n-2}
\frac{\bigl(\Gamma(\frac{n}{2})\bigr)^2}{\Gamma(n)},\]

&lt;p&gt;in particular \(I_{2n+2} = 2(2\pi)^{2n} \frac{(n!)^2}{(2n+2)!}\), my
conjecture! My faith wasn’t misplaced; by faith we understand the
universe.&lt;/p&gt;

&lt;h2 id=&quot;more&quot;&gt;More?&lt;/h2&gt;

&lt;p&gt;These kinds of explicit integral expressions are somewhat unusual in
research mathematics. In fact, some follow-up work by other
mathematicians lightly criticized our approach as “curious”.&lt;/p&gt;

&lt;p&gt;But I had fun with my integral. Just not enough fun to stay in
research mathematics.&lt;/p&gt;

&lt;p&gt;My co-author Martin Gebert pushed the underlying physics question much
further. Curiously, that yielded more interesting integrals, one of
which I’ll describe below.&lt;/p&gt;

&lt;h4 id=&quot;the-hilbert-matrix&quot;&gt;The Hilbert Matrix&lt;/h4&gt;

&lt;p&gt;As an aside, the Rosenblum operator \(T\) turns out to show up in
other disguises. For instance, the “infinite matrix”&lt;/p&gt;

\[H =
\begin{pmatrix}
1 &amp;amp; \frac{1}{2} &amp;amp; \frac{1}{3} &amp;amp; \frac{1}{4} &amp;amp; \cdots \\
\frac{1}{2} &amp;amp; \frac{1}{3} &amp;amp; \frac{1}{4} &amp;amp; \iddots \\
\frac{1}{3} &amp;amp; \frac{1}{4} &amp;amp; \iddots \\
\frac{1}{4} &amp;amp; \iddots \\
\vdots
\end{pmatrix}\]

&lt;p&gt;is known as the &lt;em&gt;Hilbert matrix&lt;/em&gt;. Its entries at position \(j, k\) are
\(\frac{1}{j + k - 1}\). In numerical analysis, it
usually serves as a cautionary tale about ill-conditioned systems.&lt;/p&gt;

&lt;p&gt;Since the entries depend only on \(j+k\), they are constant along the
anti-diagonals. Matrices with this property are called &lt;em&gt;Hankel
matrices&lt;/em&gt;. The Hilbert matrix is the most famous example; below we
will see others.&lt;/p&gt;

&lt;p&gt;On the space \(\ell_2(\N)\) of square-summable sequences, it turns out
this matrix is &lt;em&gt;unitarily equivalent&lt;/em&gt; (aka essentially the same under
a Hilbert space isomorphism) to Rosenblum’s integral operator \(T\).&lt;sup id=&quot;fnref:laguerre&quot; role=&quot;doc-noteref&quot;&gt;&lt;a href=&quot;#fn:laguerre&quot; class=&quot;footnote&quot; rel=&quot;footnote&quot;&gt;2&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;

&lt;p&gt;Lots of beautiful mathematics and hidden connections lurk behind these
objects.&lt;/p&gt;

&lt;h2 id=&quot;the-dirichlet-integral&quot;&gt;The Dirichlet integral&lt;/h2&gt;

&lt;p&gt;The improper integral&lt;/p&gt;

\[\int_0^\infty \frac{\sin x}{x} \d x = \frac{\pi}{2}\]

&lt;p&gt;is a well-known classical result known as the &lt;a href=&quot;https://en.wikipedia.org/wiki/Dirichlet_integral&quot;&gt;Dirichlet
integral&lt;/a&gt;. It’s also the
final integral exercise in the above list of 42 integrals to solve.&lt;/p&gt;

&lt;p&gt;Dirichlet’s integral is “improper” in the sense that
the integrand \(\sinc(x) = \frac{\sin x}{x}\) isn’t actually integrable (the
integral \(\int_0^\infty \abs{\sinc(x)}\d x\) isn’t finite). While the
specific limit \(\lim_{L\to\infty}\int_0^L \sinc(x)\d x\) exists, that
is due to cancellation from the sign change of \(\sin\). This
cancellation depends on how the limit is done; this makes \(\sinc\)
not Lebesgue-integrable on unbounded intervals.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Proof via Laplace transform. &lt;/strong&gt;
One way to prove Dirichlet’s identity is to use an &lt;a href=&quot;https://en.wikipedia.org/wiki/Abelian_and_Tauberian_theorems&quot;&gt;Abelian
theorem&lt;/a&gt;
which in this form is also known as the &lt;a href=&quot;https://en.wikipedia.org/wiki/Final_value_theorem&quot;&gt;“final value theorem” of the
Laplace
transform&lt;/a&gt;. It
states that &lt;em&gt;if&lt;/em&gt; the limit \(\lim_{L\to\infty} \int_0^L \frac{\sin
x}{x}\d x\) exists, its value is the same as the limit of the
regularization of its integrand via the Laplace transform&lt;sup id=&quot;fnref:3&quot; role=&quot;doc-noteref&quot;&gt;&lt;a href=&quot;#fn:3&quot; class=&quot;footnote&quot; rel=&quot;footnote&quot;&gt;3&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;

\[\lim_{s \downarrow 0} \int_0^\infty e^{-st} \frac{\sin(t)}{t} \d t.\]

&lt;p&gt;This expression can be evaluated for \(s &amp;gt; 0\) with Laplace transform
tricks (essentially differentiating by \(s\) to turn this into the
Laplace transform of \(\sin\) itself). Its value turns out to be
\(\frac{\pi}{2} - \arctan s\) and the \(\arctan\) term goes to zero as
\(s\to 0\).&lt;/p&gt;

&lt;p&gt;This used an “Abelian theorem” which requires the existence of the original
limit as one of its ingredients. In this case, the existence is
provided by, appropriately enough, &lt;a href=&quot;https://en.wikipedia.org/wiki/Dirichlet%27s_test&quot;&gt;Dirichlet’s
test&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;It’s also an example of a common pattern in mathematics (which is also
the main approach in my PhD thesis): The quantity of interest is not
quite well behaved, but it’s the limit of well-behaved expressions. So
one does a “regularization” (in this case the Laplace transform) which
turns it into a well-behaved expression, does the required
calculations there, then goes back to something like the
original. There is extra work involved in doing and undoing the
regularization, but the benefit is that the main work can be done in a
better space.&lt;/p&gt;

&lt;p&gt;With some help by ChatGPT, I recently learned about a less common
proof for Dirichlet’s identity which turned out to be directly
generalizable to another related tricky \(n\)-dimensional
integral. Instead of an Abelian theorem, it uses Cauchy’s integral
theorem and an explicit calculation with &lt;a href=&quot;https://en.wikipedia.org/wiki/Hyperbolic_functions&quot;&gt;hyperbolic
functions&lt;/a&gt;. Since
it’s somewhat fun, I’ll write it down here. This proof might look a bit
lengthy, but like Wagner’s music it’s not as bad as it sounds:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Proof via Cauchy’s integral theorem. &lt;/strong&gt;
Set \(I(L) := \int_0^L \frac{\sin x}{x}\d x\).
Since
\(\frac{\sin x}{x}=\frac12\int_{-1}^{1}e^{ixt}\,dt,\)
Fubini and the substitution \(t = \tanh(s/2)\) where \(\d t = w(s) \d
s\) for \(w(s) = \frac{1}{2}\sech^2(s/2)\) give&lt;/p&gt;

\[I(L)
= \frac{1}{2}\int_{-1}^1 \int_0^L e^{ixt}\,\d x \,\d t
= \frac{1}{2}\int_{-1}^1 D_L(t)\,\d t
= \frac{1}{2}\int_\R w(s) D_L(\tanh\tfrac{s}{2}) \,\d s\]

&lt;p&gt;with \(D_L(t) := \int_0^L e^{ixt}\dx =
\frac{e^{iLt} - 1}{it}\) where \(D_L(0) := L\) makes this function
entire.&lt;/p&gt;

&lt;p&gt;Now, shift the domain of integration from \(\R\) to \(\R + i\pi/2\)
via Cauchy’s integral theorem. For \(R &amp;gt; 0\) we will use expanding
boxes \([-R, R] + i[0, \frac{\pi}{2}]\) on the complex plane. On the
full strip \(0 \le \Im z \le \frac{\pi}{2}\) all functions involved
are holomorphic and therefore&lt;/p&gt;

\[\int_{-R}^R w(s) D_L(\tanh\tfrac{s}{2}) \,\d s
+ \int_0^{\pi/2} w(R+i\beta) D_L(\tanh(\tfrac{R+i\beta}{2})) \,\d\beta
=
\int_{-R}^R w(s + i\tfrac{\pi}{2}) D_L(\tanh(\tfrac{s}{2} +
i\tfrac{\pi}{4})) \,\d s
+ \int_0^{\pi/2} w(-R+i\beta) D_L(\tanh(\tfrac{-R+i\beta}{2})) \,\d\beta.\]

&lt;p&gt;Now, since&lt;/p&gt;

\[\Im\tanh(\tfrac{s+i\beta}{2}) = \frac{\sin\beta}{\cosh s + \cos\beta}
\ge 0,\]

&lt;p&gt;we have \(\abs{D_L(\tanh z)} \le L\) anywhere on the strip. On the vertical
sides of the box, one has&lt;/p&gt;

\[\abs{w(\pm R + i\beta)} = \frac{1}{\cosh R + \cos\beta} \le
\frac{1}{\cosh R} = \sech R \to 0 \where{R\to\infty}.\]

&lt;p&gt;So the vertical parts of the contour vanish in the \(R\to\infty\)
limit, and&lt;/p&gt;

\[I(L) = \frac{1}{2}\int_\R w(s + i\tfrac{\pi}{2}) D_L(\tanh(\tfrac{s}{2} +
i\tfrac{\pi}{4})) \,\d s.\]

&lt;p&gt;We have shifted the integration domain up by \(\pi/2\) in the complex
plane without changing the value of the integral. This had the effect
of making the functions \(D_L\) well-behaved:
For \(\Im z &amp;gt; 0\) we have both \(\abs{D_L(z)} \le \frac{2}{\abs{z}}\)
and \(D_L(z) \to \frac{i}{z}\) as \(L\to\infty\). Additionally&lt;/p&gt;

\[\frac{w(z)}{\tanh(z/2)} = \frac{1}{\sinh z}.\]

&lt;p&gt;Since \(\tanh(\tfrac{s}{2} + i\tfrac{\pi}{4}) =
\frac{\sinh s + i}{\cosh s} = \tanh s + i \sech s\) and \(\sech s &amp;gt;
0\), this bounds the integrand by&lt;/p&gt;

\[\frac{2}{\abs{\sinh(s + i\pi/2)}} = \frac{2}{\cosh s}\]

&lt;p&gt;which is integrable, so the dominated convergence theorem gives&lt;/p&gt;

\[\lim_{L\to\infty} I(L)
= \frac{i}{2}\int_\R \frac{\d s}{\sinh(s + i\pi/2)}
= \frac{i}{2}\int_\R\frac{\d s}{i\cosh s}
= \frac{1}{2}\int_\R\sech s \,\d s
= \frac{1}{2}\arctan(\sinh s) \Bigr\rvert_{s=-\infty}^\infty = \frac{\pi}{2}.\]

&lt;h2 id=&quot;a-generalization-of-the-dirichlet-integral&quot;&gt;A generalization of the Dirichlet integral&lt;/h2&gt;

&lt;p&gt;It turns out that in connection to the same quantum mechanical
phenomenon that led to the \(I_n\) integral, the cyclic integral&lt;/p&gt;

\[S_n = \lim_{L\to\infty} \int_{(0, L)^n} \prod_{j=1}^n \frac{\sin(x_j +
x_{j+1})}{x_j + x_{j+1}} \,\d x \where{n \in 2\N + 1}\]

&lt;p&gt;pops up, where \(x_{n+1} := x_1\). Some time after Martin Gebert showed
me this, I could show \(S_3 = \frac{\pi^3}{16}\) using a Laplace
transform in a somewhat &lt;a href=&quot;https://math.stackexchange.com/a/4661524/5051&quot;&gt;lengthy Stack Exchange
answer&lt;/a&gt;. But that
method doesn’t extend to general odd \(n\). From numerics, the
conjecture \(S_n = \frac{\pi^n}{2^{n+1}}\) seemed likely.&lt;/p&gt;

&lt;p&gt;I attempted to apply Hankel operator diagonalizations from the
literature. That seemed tempting because it worked for \(I_n\) and the
operator with \(\sinc\) kernel is understood in the literature – it’s been
studied by Krein and others and while it’s not well-behaved (in
particular, it’s not trace class, or even compact), it is the &lt;em&gt;limit&lt;/em&gt;
of well-behaved operators. The integral \(S_n\) is the limit of a
sequence of traces of operators. The limit operator is closely related
to the Rosenblum operator / Hilbert matrix from \(I_n\).&lt;/p&gt;

&lt;p&gt;Viewing it as a trace is also the approach most LLMs go for when asked this
question.&lt;sup id=&quot;fnref:llms&quot; role=&quot;doc-noteref&quot;&gt;&lt;a href=&quot;#fn:llms&quot; class=&quot;footnote&quot; rel=&quot;footnote&quot;&gt;4&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;

&lt;p&gt;I tried operator theoretic approaches for a while and learned a good
deal about Hankel operators and Hardy spaces. But I did not manage to
make real headway with this. Since the limit isn’t trace
class, most usual tools don’t apply and regularizations of the
operator were too complicated for me to do enough analysis on.&lt;/p&gt;

&lt;p&gt;I will still describe some of the math I learned since I found it
interesting and to show why Hankel operators looked tempting for this
problem. The actual solution for \(S_n\) (in the final section below)
turned out to be more elementary.&lt;/p&gt;

&lt;h3 id=&quot;more-hankel-matrices-and-operators&quot;&gt;More Hankel matrices and operators&lt;/h3&gt;

&lt;p&gt;Above, we learned that Rosenblum’s operator relates to the Hilbert matrix:&lt;/p&gt;

&lt;h4 id=&quot;hilbert-matrix-and-rosenblums-operator&quot;&gt;Hilbert matrix and Rosenblum’s operator&lt;/h4&gt;

\[\frac{1}{\pi}\begin{pmatrix}
1 &amp;amp; \frac{1}{2} &amp;amp; \frac{1}{3} &amp;amp; \frac{1}{4} &amp;amp; \cdots \\
\frac{1}{2} &amp;amp; \frac{1}{3} &amp;amp; \frac{1}{4} &amp;amp; \iddots \\
\frac{1}{3} &amp;amp; \frac{1}{4} &amp;amp; \iddots \\ \vdots
\end{pmatrix}

\quad\longleftrightarrow\quad

\frac{1}{\pi}\int_0^\infty \frac{e^{-(x+y)/2}}{x+y} f(y) \, \d y\]

&lt;p&gt;With a \(\frac{1}{\pi}\) normalization, this operator has spectrum \([0, 1]\).&lt;/p&gt;

&lt;h4 id=&quot;carleman-operator&quot;&gt;Carleman operator&lt;/h4&gt;

&lt;p&gt;If we take the Hilbert matrix but put zeros into every other
anti-diagonal, it becomes unitarily equivalent to the &lt;em&gt;Carleman
operator&lt;/em&gt; \(\int_0^\infty \frac{f(y)}{x+y}dy\). Power (1980) shows
this via a chain of equivalences through the Hardy spaces
\(H_2(\R)\) and \(H_2(\C_{\Im&amp;gt;0})\):&lt;/p&gt;

\[\frac{2}{\pi}
\begin{pmatrix}
1 &amp;amp; 0 &amp;amp; \frac{1}{3} &amp;amp; 0 &amp;amp; \frac{1}{5} \\
0 &amp;amp; \frac{1}{3} &amp;amp; 0 &amp;amp; \frac{1}{5} &amp;amp; \iddots \\
\frac{1}{3} &amp;amp; 0 &amp;amp; \frac{1}{5} &amp;amp; \iddots \\ \vdots
\end{pmatrix}

\quad\longleftrightarrow\quad

\frac{1}{\pi}\int_0^\infty \frac{1}{x+y} f(y) \, \d y\]

&lt;p&gt;Carleman’s (1923) original work shows its spectrum is \([0, 1]\).&lt;/p&gt;

&lt;h4 id=&quot;kreins-example&quot;&gt;Krein’s example&lt;/h4&gt;

&lt;p&gt;The operator involved in \(S_n\) was studied by Krein and others. One
interesting read is “On Krein’s example” by Kostrykin and Makarov
(2006), where they show that it’s the Carleman operator with
alternating signs for each anti-diagonal:&lt;/p&gt;

\[\frac{2}{\pi}\begin{pmatrix}
\phantom{-}1 &amp;amp; \phantom{-}0 &amp;amp; -\frac{1}{3} &amp;amp; 0 &amp;amp; \frac{1}{5} \\
\phantom{-}0 &amp;amp; -\frac{1}{3} &amp;amp; \phantom{-}0 &amp;amp; \frac{1}{5} &amp;amp; \iddots \\
-\frac{1}{3} &amp;amp; \phantom{-}0 &amp;amp; \phantom{-}\frac{1}{5} &amp;amp; \iddots \\
\vdots
\end{pmatrix}

\quad\longleftrightarrow\quad

\frac{2}{\pi}\int_0^\infty \frac{\sin(x+y)}{x+y} f(y) \, \d y\]

&lt;p&gt;The paper shows its spectrum is \([-1, 1]\). They study it in
connection with a perturbation problem, but the sinc kernel
\(\frac{\sin(x+y)}{x+y}\) also shows up in random matrix theory and
many other places.&lt;/p&gt;

&lt;h3 id=&quot;hilbert-space-equivalences&quot;&gt;Hilbert space equivalences&lt;/h3&gt;

&lt;p&gt;I found it interesting how the various Hilbert spaces involved relate
to each other. The core idea is that via Fourier series, series in
\(\ell_2(\Z)\) or \(\ell_2(\N_0)\) relate to periodic functions, which can
be viewed as functions on the unit circle \(\T = \set{z\in\C\st
\abs{z}=1}\). These in turn can sometimes be extended to the full unit
ball. The Moebius transform turns them into functions of the real line
or upper half-plane and the Fourier transform maps them to where
the integral operators live:&lt;/p&gt;

&lt;div class=&quot;centered&quot;&gt;
  &lt;p&gt;&lt;img src=&quot;/img/hardy_commute.png&quot; alt=&quot;Hardy spaces&quot; /&gt;&lt;/p&gt;
&lt;/div&gt;

&lt;p&gt;The relevant subspaces of functions of the unit circle and unit ball
are the &lt;a href=&quot;https://en.wikipedia.org/wiki/Hardy_space&quot;&gt;Hardy spaces&lt;/a&gt;.&lt;sup id=&quot;fnref:4&quot; role=&quot;doc-noteref&quot;&gt;&lt;a href=&quot;#fn:4&quot; class=&quot;footnote&quot; rel=&quot;footnote&quot;&gt;5&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;

&lt;h2 id=&quot;the-actual-solution-for-int_0-inftyn-prod_j1n-fracsinx_j--x_j1x_j--x_j1-d-x&quot;&gt;The actual solution for \(\int_{(0, \infty)^n} \prod_{j=1}^n \frac{\sin(x_j + x_{j+1})}{x_j + x_{j+1}} \d x\)&lt;/h2&gt;

&lt;p&gt;It’s 2026 and LLMs are now truly useful for mathematics. The main
bottleneck is that their proofs are still often wrong, too
complicated, or incomplete. Carefully verifying their output is at
this point still required and often tedious.&lt;/p&gt;

&lt;p&gt;However, I found that ChatGPT 5.5 Extended Pro was eventually able to
give me something useful for the \(S_n\) integral. Its first several
approaches were both handwavy and complicated, but after I confronted
it with its own shortcomings often enough it produced the outline of a
correct and elementary proof.&lt;/p&gt;

&lt;p&gt;The same approach of moving the integration domain into the complex
plane using Cauchy’s integral theorem that shows the Dirichlet
integral identity above turns out to work for \(S_n\). (In fact, I
wrote the Dirichlet integral solution after that approach solved
\(S_n\).) Using \(\frac{\sin y}{y}=\frac12\int_{-1}^{1}e^{ity}\,dt\)
and the substitution \(t = \tanh(s/2)\) one can shift the contour up
by \(\pi/2\). For odd \(n\), the \(L\to\infty\) limit then turns into
a product of \(\sech\) integrals. The conjecture \(S_n =
\frac{\pi^n}{2^{n+1}}\) is correct. For the
details, see &lt;a href=&quot;https://math.stackexchange.com/a/5140024/5051&quot;&gt;this Stack Exchange
answer&lt;/a&gt;.&lt;sup id=&quot;fnref:InGPT&quot; role=&quot;doc-noteref&quot;&gt;&lt;a href=&quot;#fn:InGPT&quot; class=&quot;footnote&quot; rel=&quot;footnote&quot;&gt;6&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;

&lt;p&gt;Given that \(I_n\) and \(S_n\) are really a countably infinite number
of integrals, I believe I finally did enough integrals now.&lt;/p&gt;

&lt;h2 id=&quot;bibliography&quot;&gt;Bibliography&lt;/h2&gt;

&lt;ul class=&quot;simplelist&quot;&gt;
  &lt;li&gt;T. Carleman, &lt;em&gt;Sur les équations intégrales singulières à noyau réel et symétrique&lt;/em&gt;, Almqvist and Wiksell, Uppsala, 1923. &lt;em&gt;(Introduces and analyzes the \(\frac{1}{\pi(x+y)}\) operator; determines its spectrum as \([0,1]\).)&lt;/em&gt;&lt;/li&gt;
  &lt;li&gt;D. Hilbert, “Ein Beitrag zur Theorie des Legendre’schen Polynoms,” &lt;em&gt;Acta Mathematica&lt;/em&gt; &lt;strong&gt;18&lt;/strong&gt; (1894), 155–159. &lt;em&gt;(Original appearance of the Hilbert matrix.)&lt;/em&gt;&lt;/li&gt;
  &lt;li&gt;H. Küttler, “Anderson’s Orthogonality Catastrophe,” dissertation, Ludwig-Maximilians-Universität München, 2014.&lt;/li&gt;
  &lt;li&gt;V. Kostrykin and K. A. Makarov, “On Krein’s example,” arXiv:math/0606249 (2006). &lt;em&gt;(Proves the sinc-kernel operator \(K_\mu\) has purely absolutely continuous spectrum \([-1,1]\); makes the connection to Hankel operator theory via Power’s results explicit.)&lt;/em&gt;&lt;/li&gt;
  &lt;li&gt;S. C. Power, “Hankel operators on Hilbert space,” &lt;em&gt;Bulletin of the London Mathematical Society&lt;/em&gt; &lt;strong&gt;12&lt;/strong&gt; (1980), 422–442. &lt;em&gt;(Excellent survey; contains the explicit unitary equivalence chain from the alternating matrix to Carleman’s operator.)&lt;/em&gt;&lt;/li&gt;
  &lt;li&gt;M. Rosenblum, “On the Hilbert matrix, I,” &lt;em&gt;Proceedings of the American Mathematical Society&lt;/em&gt; &lt;strong&gt;9&lt;/strong&gt; (1958), 137–140. &lt;em&gt;(Identifies the \(L_2(0,\infty)\) operator via Laguerre functions and Whittaker functions.)&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;div class=&quot;footnotes&quot; role=&quot;doc-endnotes&quot;&gt;
  &lt;ol&gt;
    &lt;li id=&quot;fn:1&quot; role=&quot;doc-endnote&quot;&gt;
      &lt;p&gt;If you need to know, &lt;em&gt;Anderson’s orthogonality catastrophe&lt;/em&gt; —
a phenomenon where the ground states of a Fermi
gas before and after a tiny perturbation become &lt;em&gt;orthogonal&lt;/em&gt; to
each other as the system grows large. The overlap between them
decays as a power law, and expanding the exponent into a series
expression produced the integral \(I_n\) for the \(n\)th term.
But you don’t actually need to know any of that. &lt;a href=&quot;#fnref:1&quot; class=&quot;reversefootnote&quot; role=&quot;doc-backlink&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
    &lt;li id=&quot;fn:laguerre&quot; role=&quot;doc-endnote&quot;&gt;
      &lt;p&gt;The orthonormal basis of \(L_2(0,\infty)\) that makes this
         correspondence to the Hilbert matrix work is given by the
         weighted &lt;a href=&quot;https://en.wikipedia.org/wiki/Laguerre_polynomials&quot;&gt;Laguerre
         polynomials&lt;/a&gt;
         \(\phi_n(x) = e^{-x/2}L_n(x)\). &lt;a href=&quot;#fnref:laguerre&quot; class=&quot;reversefootnote&quot; role=&quot;doc-backlink&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
    &lt;li id=&quot;fn:3&quot; role=&quot;doc-endnote&quot;&gt;
      &lt;p&gt;The Laplace transform and Abelian and Tauberian theorems for it
  also underlie the proof of the &lt;a href=&quot;https://en.wikipedia.org/wiki/Prime_number_theorem&quot;&gt;prime number
  theorem&lt;/a&gt;
  which involves controlling certain expressions involving
  Riemann’s \(\zeta\) function. &lt;a href=&quot;#fnref:3&quot; class=&quot;reversefootnote&quot; role=&quot;doc-backlink&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
    &lt;li id=&quot;fn:llms&quot; role=&quot;doc-endnote&quot;&gt;
      &lt;p&gt;E.g., Opus 4.8 approaches this as traces of operators. Fable
     5 eventually tried another approach, but it was also &lt;a href=&quot;https://x.com/HeinrichKuttler/status/2064467693370273844?s=20&quot;&gt;complicated and
     incomplete&lt;/a&gt;. &lt;a href=&quot;#fnref:llms&quot; class=&quot;reversefootnote&quot; role=&quot;doc-backlink&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
    &lt;li id=&quot;fn:4&quot; role=&quot;doc-endnote&quot;&gt;
      &lt;p&gt;Incidentally, it’s a more complicated version of Hardy spaces
that Louis de Branges tried to use in his claimed proof for the famous
Riemann hypothesis. I found &lt;a href=&quot;https://eric.kvaalen.com/papers/DeBrangesMethod/&quot;&gt;this
writeup&lt;/a&gt;
somewhat interesting, and the &lt;a href=&quot;https://en.wikipedia.org/wiki/Louis_de_Branges_de_Bourcia#Controversial_claims_of_solutions_to_unsolved_problems&quot;&gt;relevant section of
Wikipedia&lt;/a&gt;
almost hilarious. &lt;a href=&quot;#fnref:4&quot; class=&quot;reversefootnote&quot; role=&quot;doc-backlink&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
    &lt;li id=&quot;fn:InGPT&quot; role=&quot;doc-endnote&quot;&gt;
      &lt;p&gt;In fact, ChatGPT also can do the original integral \(I_n\)
in a more elementary way &lt;a href=&quot;https://chatgpt.com/s/t_6a34d486c88c8191a502919a68438854&quot;&gt;when
asked&lt;/a&gt;. &lt;a href=&quot;#fnref:InGPT&quot; class=&quot;reversefootnote&quot; role=&quot;doc-backlink&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
  &lt;/ol&gt;
&lt;/div&gt;
</description>
        <pubDate>Thu, 18 Jun 2026 00:00:00 +0000</pubDate>
        <link>https://heiner.ai/blog/2026/06/18/some-specific-integrals.html</link>
        <guid isPermaLink="true">https://heiner.ai/blog/2026/06/18/some-specific-integrals.html</guid>
        
        
        <category>blog</category>
        
      </item>
    
      <item>
        <title>The chain rule, Jacobians, autograd, and shapes</title>
        <description>
&lt;div class=&quot;right&quot;&gt;
  &lt;p&gt;&lt;cite&gt;“Man muss immer umkehren”&lt;/cite&gt; &lt;br /&gt;
– Carl Gustav Jacob Jacobi&lt;sup id=&quot;fnref:1&quot; role=&quot;doc-noteref&quot;&gt;&lt;a href=&quot;#fn:1&quot; class=&quot;footnote&quot; rel=&quot;footnote&quot;&gt;1&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;
&lt;/div&gt;

&lt;p&gt;This is a short explainer about the chain rule and autograd in PyTorch and JAX,
from the perspective of a mathematical user.&lt;/p&gt;

&lt;div class=&quot;floated centered&quot;&gt;
  &lt;p&gt;&lt;img src=&quot;/img/jacobi.jpeg&quot; alt=&quot;Carl Gustav Jacob Jacobi&quot; style=&quot;width:200px;&quot; /&gt;
&lt;br /&gt;&lt;/p&gt;
  &lt;s&gt;The Joker&lt;/s&gt;
  &lt;p&gt;Carl Gustav Jacob Jacobi&lt;/p&gt;
  &lt;div class=&quot;small&quot;&gt;
    &lt;p&gt;(1804 – 1851)&lt;br /&gt;
“Die Haare immer nach hinten kehren”&lt;br /&gt;
Image source: &lt;a href=&quot;https://en.wikipedia.org/wiki/Carl_Gustav_Jacob_Jacobi#/media/File:Carl_Jacobi.jpg&quot;&gt;Wikipedia&lt;/a&gt;&lt;/p&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;There are many, many explanations of this on the web. Many are likely
better than this one. I’ll still write my own, which in the spirit of
this blog is meant to be written, not read. I’ll also don’t focus on
the implementation of the system, just on its observable behavior.&lt;/p&gt;

&lt;p&gt;Other, perhaps better sources for the same info are:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://pytorch.org/tutorials/beginner/blitz/autograd_tutorial.html#sphx-glr-beginner-blitz-autograd-tutorial-py&quot;&gt;A gentle introduction to
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.autograd&lt;/code&gt;&lt;/a&gt;
from the tutorials at pytorch.org.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://pytorch.org/docs/stable/notes/autograd.html&quot;&gt;Autograd
mechanics&lt;/a&gt;
from pytorch.org.&lt;/li&gt;
  &lt;li&gt;Zachary DeVito’s excellent &lt;a href=&quot;https://colab.research.google.com/drive/1VpeE6UvEPRz9HmsHh1KS0XxXjYu533EC&quot;&gt;colab with an example implementation
of reverse-mode
autodiff&lt;/a&gt;
from scratch. I highly recommend studying this one.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://jax.readthedocs.io/en/latest/notebooks/autodiff_cookbook.html&quot;&gt;The Autodiff
Cookbook&lt;/a&gt;
in the JAX docs. Also very good.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The JAX docs especially are delightfully mathematical. There are many more
sources on the web. I like the more extensive treatment is in &lt;a href=&quot;https://mediatum.ub.tum.de/doc/1638886/document.pdf#page=25&quot;&gt;Thomas Frerix’s
PhD thesis&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Still, let me add my own spin on the issue. One reason is that many
other articles write things like &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dL/dOutputs&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dL/dInputs&lt;/code&gt; and
generallly use a “variable”-based notation that, while entirely
reasonable from an implementation standpoint, would &lt;a href=&quot;https://twitter.com/HeinrichKuttler/status/1262337725161771009&quot;&gt;make Spivak
sad&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;the-chain-rule&quot;&gt;The chain rule&lt;/h2&gt;

&lt;p&gt;All of “deep learning”, and most of Physics, depends on this theorem
discovered by Leibniz ca. 1676.&lt;/p&gt;

&lt;h3 id=&quot;one-dimensional-functions&quot;&gt;One dimensional functions&lt;/h3&gt;

&lt;p&gt;Given two differentiable functions \(f,g\from\R\to\R\), the chain rule
says&lt;/p&gt;

\[(g\circ f)&apos;(x) = g&apos;(f(x))f&apos;(x)  \where{x\in\R}. \label{eq:cr1}\tag{1}\]

&lt;p&gt;Here, \((g\circ f)(x) = g(f(x))\) is the composition, i.e., chained
evaluation of first \(y = f(x)\), then \(g(y)\).&lt;/p&gt;

&lt;h3 id=&quot;multidimensional-functions&quot;&gt;Multidimensional functions&lt;/h3&gt;

&lt;p&gt;It’s one of the wonders of analysis that this rule keeps being correct
for differentiable multidimensional functions \(f\from\R^n\to\R^m\),
\(g\from\R^m\to\R^k\) if “differentiable” is defined
correctly. Skipping over some technicalities, this requires \(f\) and
\(g\) to be &lt;em&gt;totally differentiable&lt;/em&gt; (also called
&lt;em&gt;Fréchet differentiable&lt;/em&gt;), which implies that all components
\(f_j\from\R^n\to\R\) are partially differentiable; the derivative
\(f&apos;(a)\) for \(a\in\R^n\) can then be shown to be equal to the
&lt;em&gt;Jacobian matrix&lt;/em&gt;&lt;/p&gt;

\[f&apos;(a) = J_f(a)
 := \bigl(\partial_k f_j(a)\bigr)_{\substack{j=1,\ldots,m\\ k=1,\ldots,n}}
  = \begin{pmatrix}
      \partial_1 f_1(a) &amp;amp; \cdots &amp;amp; \partial_n f_1(a) \\
      \vdots &amp;amp;&amp;amp; \vdots \\
      \partial_1 f_m(a) &amp;amp; \cdots &amp;amp; \partial_n f_m(a)
    \end{pmatrix}
    \in\R^{m\times n}.\]

&lt;p&gt;The idea is to view \(f(a) = (f_1(a), \ldots, f_m(a))^\top\in\R^m\)
as a column vector and add one column per partial derivative, i.e.,
dimension of its input \(a\).&lt;/p&gt;

&lt;p&gt;With this definition, the multidimensional chain rule reads like its
1D version \(\eqref{eq:cr1}\),&lt;/p&gt;

\[(g\circ f)&apos;(x) = g&apos;(f(x))\cdot f&apos;(x)  \where{x\in\R^n}.  \label{eq:crN}\tag{2}\]

&lt;p&gt;However, in this case this is the matrix multiplication
\(\cdot\from\R^{k\times m}\times\R^{m\times n}\to\R^{k\times n}\) of
\(J_g(f(x))\) and \(J_f(x)\) and their order is important. Jacobi
would have called this &lt;em&gt;nachdifferenzieren&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Via the nature of this rule it iterates, i.e. the derivative of the
composition \(h\circ g\circ f\) is&lt;/p&gt;

\[(h\circ g\circ f)&apos;(x)
=
h&apos;(g(f(x)))\cdot g&apos;(f(x))\cdot f&apos;(x)
=
(h&apos;\circ g\circ f)(x)\cdot (g&apos;\circ f)(x)\cdot f&apos;(x),\]

&lt;p&gt;and likewise for a composition of \(n\) functions&lt;/p&gt;

\[(f_n\circ \cdots \circ f_1)&apos;(x)
=
(f_n&apos;\circ f_{n-1}\circ\cdots\circ f_1)(x)\cdot
(f_{n-1}&apos;\circ f_{n-2}\circ\cdots\circ f_1)(x)
\,\cdots\,
(f_2&apos;\circ f_1)(x) \cdot f_1&apos;(x).  \label{eq:crNn}\tag{3}\]

&lt;p&gt;Note that subscripts no longer mean components here, we are talking
about \(n\) functions, each with multidimensional inputs and outputs.&lt;/p&gt;

&lt;h3 id=&quot;backprop&quot;&gt;Backprop&lt;/h3&gt;

&lt;p&gt;Now, while matrix multiplication isn’t commutative, meaning in general
\(AB \ne BA\), it is associative: For a product of several matrices
\(ABC\), it does not matter if one computes \((AB)C\) or \(A(BC)\);
this is what makes the notation \(ABC\) sensible in the first
place. However, this only means the same output is produced by those
two alternatives. It does not mean the same amount of “work” (or
“compute”) went into either case.&lt;/p&gt;

&lt;p&gt;Counting scalar operations, a product \(AB\) with
\(A\in\R^{k\times m}\) and \(B\in\R^{m\times n}\) takes \(nkm\)
multiplications and \(nk(m-1)\) additions, since each entry in the
output matrix is the sum of \(m\) multiplications. In a chain of
matmuls like \(ABCDEFG\cdots\), it’s clear that some groupings like
\(((AB)(CD))(E(FG))\cdots\) might be better than others. In
particular, there may well be better and worse ways of computing the
Jacobian \(\eqref{eq:crNn}\). However, to quote
&lt;a href=&quot;https://en.wikipedia.org/wiki/Automatic_differentiation#Beyond_forward_and_reverse_accumulation&quot;&gt;Wikipedia&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;The problem of computing a full Jacobian of \(f\from\R^n\to\R^m\) with a
minimum number of arithmetic operations is known as the optimal
Jacobian accumulation (OJA) problem, which is NP-complete.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The good news is that in important special cases, this problem is
easy. In particular, if the first matrix in the product has only one
row, or the last only one column, it makes sense to compute the
product “from the left” or “from the right”, respectively. And those
cases are not particularly pathological either, as they correspond to
either the final function \(f_n\) mapping to a scalar or the whole
composition depending only on a scalar input \(x\in\R\). The former
case is especially important as that’s what happens whenever we
compute the gradients of a scalar &lt;em&gt;loss function&lt;/em&gt;, such as in bascially all
cases where neural networks are used.&lt;sup id=&quot;fnref:2&quot; role=&quot;doc-noteref&quot;&gt;&lt;a href=&quot;#fn:2&quot; class=&quot;footnote&quot; rel=&quot;footnote&quot;&gt;2&lt;/a&gt;&lt;/sup&gt;
The corresponding orders of multiplications in the chain rule
\(\eqref{eq:crNn}\) are known as
&lt;em&gt;reverse mode&lt;/em&gt; or &lt;em&gt;forward mode&lt;/em&gt;, respectively. Ignoring some
distinctions not relevant here, reverse mode is also known as
&lt;em&gt;backpropagation&lt;/em&gt;, or &lt;em&gt;backprop&lt;/em&gt; for short.&lt;/p&gt;

&lt;p&gt;In this case, the image of \(f_n\) is one dimensional, and therefore
its Jacobian matrix \(f_n&apos;\) has only one row – it’s a row
vector. After multiplication with the next Jacobian \(f_{n-1}&apos;\), this
property is preserved: All matmuls in the chain turn into
&lt;em&gt;vector-times-matrix&lt;/em&gt;. Specifically, they are
vector-times-Jacobian-matrix, more commonly known as a vector-Jacobian
product, or VJP. To illustrate:&lt;/p&gt;

\[\begin{pmatrix}
  \unicode{x2E3B}
\end{pmatrix}_1
\begin{pmatrix}
  | &amp;amp; | &amp;amp; | \\
  | &amp;amp; | &amp;amp; | \\
  | &amp;amp; | &amp;amp; |
\end{pmatrix}_2
\begin{pmatrix}
  | &amp;amp; | &amp;amp; | \\
  | &amp;amp; | &amp;amp; | \\
  | &amp;amp; | &amp;amp; |
\end{pmatrix}_3
\cdots
\begin{pmatrix}
  | &amp;amp; | &amp;amp; | \\
  | &amp;amp; | &amp;amp; | \\
  | &amp;amp; | &amp;amp; |
\end{pmatrix}_n
=
\begin{pmatrix}
  \unicode{x2E3B}
\end{pmatrix}
\begin{pmatrix}
  | &amp;amp; | &amp;amp; | \\
  | &amp;amp; | &amp;amp; | \\
  | &amp;amp; | &amp;amp; |
\end{pmatrix}_3
\cdots
\begin{pmatrix}
  | &amp;amp; | &amp;amp; | \\
  | &amp;amp; | &amp;amp; | \\
  | &amp;amp; | &amp;amp; |
\end{pmatrix}_n
=
\text{etc.}\]

&lt;p&gt;What this means is that for neural network applications, a system like
PyTorch or JAX &lt;em&gt;doesn’t need to actually compute&lt;/em&gt; full Jacobians – all
it needs are vector-Jacobian products. It turns out that
(classic) PyTorch does and can in fact do nothing else.&lt;/p&gt;

&lt;p&gt;Also notice that the row vector
\(\begin{pmatrix}\unicode{x2E3B}\end{pmatrix}\) multiplied from the
left is “output-shaped” from the perspective of the Jacobian it gets
multiplied to. This is the reason &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;grad_output&lt;/code&gt; in PyTorch always has
the shape of the operation’s output and why
&lt;a href=&quot;https://pytorch.org/docs/stable/generated/torch.Tensor.backward.html&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.Tensor.backward&lt;/code&gt;&lt;/a&gt;
receives an argument described as the “gradient w.r.t. the
tensor”.&lt;/p&gt;

&lt;p&gt;You may wonder what it means for it to have a specific shape vs just
being a “flat” row vector as it is here. I certainly wondered about
this; the answer is below.&lt;/p&gt;

&lt;h2 id=&quot;in-pytorch&quot;&gt;In PyTorch&lt;/h2&gt;

&lt;p&gt;Here’s a very simple PyTorch example (lifted from
&lt;a href=&quot;https://medium.com/@monadsblog/pytorch-backward-function-e5e2b7e60140&quot;&gt;here&lt;/a&gt;):&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;torch&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;requires_grad&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;empty&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;3.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# VJP.
&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;y:&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;x.grad:&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Manual computation.
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dydx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]],&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;equal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dydx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;In PyTorch. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Tensor.backward&lt;/code&gt; computes the backward pass via
vector-Jacobian products. If the tensor in question is a scalar, an
implicit &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1&lt;/code&gt; is assumed, otherwise one has to supply a tensor of the
same shape which is used as the vector in the VJP, as in the example
above.&lt;/p&gt;

&lt;h2 id=&quot;but-wait-tensor-or-vector&quot;&gt;But wait, tensor or vector?&lt;/h2&gt;

&lt;p&gt;For the typical mathematician, the term “tensor” for the
multidimensional array in PyTorch and JAX is a bit on an acquired (or
not) taste – but to be fair, so is anything about the real tensor
product \(\otimes\) as well.&lt;/p&gt;

&lt;p&gt;The situation here seems especially confusing – the chain rule from
multidimensional calculus makes a specific point of what’s a row and
what’s a column and treats functions \(\R^n\to\R^m\) by introducing
\(m\times n\) matrices. In PyTorch, functions depend on and produce one (or
several) multidimensional “tensors”. What gives?&lt;/p&gt;

&lt;p&gt;The answer turns out to be relatively simple: The math part of the
backward pass doesn’t depend on these tensor shapes in any deep
way. Instead, it does the equivalent of “reshaping” everything into a
vector. Example:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;3.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;4.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;requires_grad&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;empty&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;3.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;4.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;6.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;y:&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# VJP.
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;x.grad:&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;What did this even compute? It’s the equivalent of reshaping inputs
and outputs to be vectors, then applying the standard calculus from
above:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;dydx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# y.reshape(-1) x x.reshape(-1) Jacobian matrix.
&lt;/span&gt;    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# y[0, 0]
&lt;/span&gt;        &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# y[0, 1]
&lt;/span&gt;        &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# y[1, 0]
&lt;/span&gt;        &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# y[1, 1]
&lt;/span&gt;        &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# y[2, 0]
&lt;/span&gt;        &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# y[2, 1]
&lt;/span&gt;    &lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;dydx&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dydx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;equal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dydx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;To be clear: PyTorch does not actually compute the Jacobian only to
multiply it from the left with this vector, but what it does has the
same output as this less efficient code.&lt;/p&gt;

&lt;h2 id=&quot;in-jax&quot;&gt;In JAX&lt;/h2&gt;

&lt;p&gt;PyTorch is great. But it’s not necessarily principled. This tweet
expresses this somewhat more aggressively:&lt;/p&gt;

&lt;blockquote class=&quot;twitter-tweet tw-align-center&quot;&gt;&lt;p lang=&quot;en&quot; dir=&quot;ltr&quot;&gt;The Aesthetician in me wants to be constantly annoyed by how ugly PyTorch is but frankly I’m consistently impressed with how easy it is to develop in.&lt;/p&gt;&amp;mdash; Aidan Clark (@_aidan_clark_) &lt;a href=&quot;https://twitter.com/_aidan_clark_/status/1568052833030897664?ref_src=twsrc%5Etfw&quot;&gt;September 9, 2022&lt;/a&gt;&lt;/blockquote&gt;
&lt;script async=&quot;&quot; src=&quot;https://platform.twitter.com/widgets.js&quot; charset=&quot;utf-8&quot;&gt;&lt;/script&gt;

&lt;p&gt;JAX is, arguably, different, at least on the first account. It comes
with vector-Jacobian products, Jacobian-vector products, and also the
option to compute full Jacobians if required. I couldn’t write up the
details better than the &lt;a href=&quot;https://jax.readthedocs.io/en/latest/notebooks/autodiff_cookbook.html&quot;&gt;JAX Autodiff
Cookbook&lt;/a&gt;
does, so I won’t try. To quote just one relevant portion, adjusted
slightly to our notation:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;The JAX function &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;vjp&lt;/code&gt; can take a Python function for evaluating \(f\)
and give us back a Python function for evaluating the VJP \((x, v)\mapsto(f(x), v^\top f&apos;(x))\).&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;so-what-does-it-really-do&quot;&gt;So what does it really do?&lt;/h2&gt;

&lt;p&gt;For the autodiff details, read either Zachary DeVito’s &lt;a href=&quot;https://colab.research.google.com/drive/1VpeE6UvEPRz9HmsHh1KS0XxXjYu533EC&quot;&gt;colab with an
example implementation of what PyTorch does&lt;/a&gt;,
or the JAX Autodiff Cookbook, or ideally both.&lt;/p&gt;

&lt;p&gt;But to round things out, let’s look at how one defines a “custom
function” with its own forward and backward pass in PyTorch.&lt;/p&gt;

&lt;p&gt;We’ll take elementwise multiplication as our first example; the fancy
mathematics name of this simple operation is
&lt;a href=&quot;https://en.wikipedia.org/wiki/Hadamard_product_(matrices)&quot;&gt;&lt;em&gt;Hadamard
product&lt;/em&gt;&lt;/a&gt;
(also known as &lt;em&gt;Schur product&lt;/em&gt; – their motto was “&lt;em&gt;name, always name&lt;/em&gt;”&lt;sup id=&quot;fnref:3&quot; role=&quot;doc-noteref&quot;&gt;&lt;a href=&quot;#fn:3&quot; class=&quot;footnote&quot; rel=&quot;footnote&quot;&gt;3&lt;/a&gt;&lt;/sup&gt;). We’ll
denote it by \(\odot.\) To fit it within the
standard calculus above, we reinterpret
\(\odot\from\R^n\times\R^n\to\R^n\) as \(\odot\from\R^{2n}\to\R^n\), multiplying
the first and second “half” of its single-vector input, i.e.,
\(\R^{2n}\ni x\mapsto\odot(x) = (x_jx_{n+j})_{j=1,\ldots,n}\in\R^n.\) Its derivative
is&lt;/p&gt;

\[\odot&apos;(x) =
  \begin{pmatrix}
    x_{n+1} &amp;amp;   &amp;amp;   &amp;amp;                &amp;amp; x_1 &amp;amp;   &amp;amp;  &amp;amp;  \\
      &amp;amp; x_{n+2} &amp;amp;   &amp;amp;                &amp;amp;   &amp;amp; x_2 &amp;amp;  &amp;amp;  \\
      &amp;amp;   &amp;amp; {\lower 3pt\smash{\ddots}}   &amp;amp;   &amp;amp;   &amp;amp;  &amp;amp; {\lower 3pt\smash{\ddots}} &amp;amp;  \\
      &amp;amp;   &amp;amp;           &amp;amp; x_{2n}       &amp;amp;   &amp;amp;   &amp;amp;  &amp;amp; x_n
  \end{pmatrix}
  \in\R^{n\times 2n},  \where{x\in\R^{2n}}\]

&lt;p&gt;where empty cells are zeros. It should be immediately obvious that
there’s no need to “materialize” these diagonal Jacobians. In fact,
given a vector \(v = (v_1, \ldots, v_{2n})\in\R^{2n}\), the VJP here
is just&lt;/p&gt;

\[v\cdot \odot&apos;(x) = (v_1x_{n+1}, \ldots, v_nx_{2n},
v_{n+1}x_1, \ldots, v_{2n}x_n) \in \R^{2n}.\]

&lt;p&gt;(And that already seems like a needless complication of such a simple
thing als elementwise multiplication!)&lt;/p&gt;

&lt;p&gt;The PyTorch version of this is … well,
it’s just &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x * y&lt;/code&gt;, and PyTorch knows full well how to compute and
differentiate that. But if we wanted for some reason to add this from
scratch, it might look like this:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;HadamardProduct&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;autograd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Function&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;Computes lhs * rhs and its backward pass.&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ctx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lhs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rhs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;ctx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;save_for_backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lhs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rhs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lhs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rhs&lt;/span&gt;

    &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ctx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad_output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;lhs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rhs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ctx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;saved_tensors&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;grad_lhs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad_output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rhs&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;grad_rhs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad_output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lhs&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad_lhs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad_rhs&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;mul&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;HadamardProduct&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;apply&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ctx&lt;/code&gt; argument is used to stash the tensors required for the
backward pass somewhere (in Zachary’s
&lt;a href=&quot;https://colab.research.google.com/drive/1VpeE6UvEPRz9HmsHh1KS0XxXjYu533EC&quot;&gt;colab&lt;/a&gt;,
this is done via a closure) and the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;grad_output&lt;/code&gt; argument is the
output-shaped “vector” of the VJP. It’s a single argument in this case
since the function has a single output. PyTorch may reuse this tensor,
so it’s important even in cases where the gradient computed has the same
shape to “NEVER modify [this argument] in-place”, as the &lt;a href=&quot;https://pytorch.org/docs/stable/notes/extending.html#how-to-use&quot;&gt;PyTorch docs
say&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Testing this:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;lhs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;requires_grad&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;rhs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;3.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;4.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;requires_grad&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mul&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lhs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rhs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;y =&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;6.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;equal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lhs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rhs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;equal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rhs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lhs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This example is typical for elementwise operations, where the
Jacobian matrices are diagonal and VJPs are just elementwise
operations themselves.&lt;/p&gt;

&lt;p&gt;To contrast this with another example, let’s look at a real, genuine,
linear function. Remember that for a matrix \(W\in\R^{m\times n}\),
the function \(\R^n\ni x \mapsto Wx \in \R^m\) is Fréchet
differentiable and its derivative is the constant \(W\).&lt;sup id=&quot;fnref:4&quot; role=&quot;doc-noteref&quot;&gt;&lt;a href=&quot;#fn:4&quot; class=&quot;footnote&quot; rel=&quot;footnote&quot;&gt;4&lt;/a&gt;&lt;/sup&gt; Taking \(x\)
as a constant and \(W=(W_{jk})_{j=1,\ldots,m;\; k=1,\ldots,n}\) as the “dependent variable”, and “reshaping to
vector form” as above, the derivative at \(W\) is&lt;/p&gt;

\[\begin{pmatrix}
      x_1 &amp;amp; \cdots &amp;amp; x_n &amp;amp;     &amp;amp;        &amp;amp;     &amp;amp;        &amp;amp;     &amp;amp;        &amp;amp; \\
          &amp;amp;        &amp;amp;     &amp;amp; x_1 &amp;amp; \cdots &amp;amp; x_n &amp;amp;        &amp;amp;     &amp;amp;        &amp;amp; \\
          &amp;amp;        &amp;amp;     &amp;amp;     &amp;amp;        &amp;amp;     &amp;amp; \ddots &amp;amp;     &amp;amp;        &amp;amp; \\
          &amp;amp;        &amp;amp;     &amp;amp;     &amp;amp;        &amp;amp;     &amp;amp;        &amp;amp; x_1 &amp;amp; \cdots &amp;amp; x_n
  \end{pmatrix}
  \in\R^{m\times nm}.\]

&lt;p&gt;Forming the VJP with a vector \(v\in\R^m\) and reshaping back to the
shape of \(W\) results in VJP of \(v\cdot x^\top\), with entries
\((v_jx_k)_{j,k}\).&lt;/p&gt;

&lt;p&gt;The PyTorch code for that is (cf. the &lt;a href=&quot;https://pytorch.org/docs/stable/notes/extending.html#example&quot;&gt;PyTorch
docs&lt;/a&gt;):&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ActuallyLinear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;autograd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Function&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ctx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;ctx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;save_for_backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;input&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;

    &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ctx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad_output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nb&quot;&gt;input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ctx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;saved_tensors&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;grad_input&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad_weight&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Checks for extra efficiency -- only compute VJP with vector != zero.
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ctx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;needs_input_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;grad_input&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad_output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ctx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;needs_input_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;grad_weight&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad_output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;unsqueeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;unsqueeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad_input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad_weight&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Testing this:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;3.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;4.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;6.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;requires_grad&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;10.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;11.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;requires_grad&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ActuallyLinear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;apply&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;y =&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;3.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Save for comparing.
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_grad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;W_grad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Reset to zero.
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;torch_linear&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Set weight without touching gradient tape.
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch_linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[...]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;torch_y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch_linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;torch_y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;equal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;equal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch_linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;one-final-comment&quot;&gt;One final comment&lt;/h2&gt;

&lt;p&gt;I could go on, but this is plenty for now. The last thing worth
mentioning is that \(\eqref{eq:crNn}\) doesn’t quite fit the actual
situation of deep neural networks, where one takes the gradient of all
weights, and each layer \(f_j\) depends both on the outputs
(“activations”) of the previous layer and its own weight, and the
inputs of the first layer \(f_1\) (and potentially some later layers,
e.g. for “targets”) are just “data”, which is treated as
a parametrization of the functions. One way to apply the Calculus 102
rule above would be to have earlier layers pass on all weights they
don’t need as an identity function (with identity matrix for that part
of its Jacobian). This can also be written in other ways, but the
&lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/CSS/margin-bottom&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;margin-bottom&lt;/code&gt;&lt;/a&gt;
here is too small to contain it.&lt;/p&gt;
&lt;div class=&quot;footnotes&quot; role=&quot;doc-endnotes&quot;&gt;
  &lt;ol&gt;
    &lt;li id=&quot;fn:1&quot; role=&quot;doc-endnote&quot;&gt;
      &lt;p&gt;Did Jacobi actually say that? Googling this is hard because
  &lt;a href=&quot;https://fs.blog/inversion/&quot;&gt;Charlie Munger likes the supposed quote so
  much&lt;/a&gt;.
  However, there’s a &lt;a href=&quot;https://www.ams.org/journals/bull/1916-23-01/S0002-9904-1916-02863-1/S0002-9904-1916-02863-1.pdf#page=3&quot;&gt;1916
  source&lt;/a&gt;
  claiming “[t]he great mathematician Jacobi is said to have
  inculcated upon his students the dictum”. A &lt;a href=&quot;https://books.google.de/books?id=pVNR7-6XeCQC&amp;amp;pg=PA1214&amp;amp;lpg=PA1214&amp;amp;dq=%22man+muss+alles+umkehren%22+jacobi&amp;amp;source=bl&amp;amp;ots=MAEDG85f23&amp;amp;sig=ACfU3U1AEZdgV7tqBzSLUxTojqAQLVihuQ&amp;amp;hl=en&amp;amp;sa=X&amp;amp;redir_esc=y#v=onepage&amp;amp;q=%22man%20muss%20alles%20umkehren%22%20jacobi&amp;amp;f=false&quot;&gt;1968 source&lt;/a&gt;
  gives a slightly different version. Perhaps it’s a
  matter of &lt;em&gt;invent, always invent&lt;/em&gt;. &lt;a href=&quot;#fnref:1&quot; class=&quot;reversefootnote&quot; role=&quot;doc-backlink&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
    &lt;li id=&quot;fn:2&quot; role=&quot;doc-endnote&quot;&gt;
      &lt;p&gt;To illustrate the extremes this is pushed to for large scale
cases: A large language model like GPT3 can have billions or even
trillions of weights (corresponding to the dimension of
\(x\in\R^n\)) but still computes a scalar (one dimensional) loss. &lt;a href=&quot;#fnref:2&quot; class=&quot;reversefootnote&quot; role=&quot;doc-backlink&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
    &lt;li id=&quot;fn:3&quot; role=&quot;doc-endnote&quot;&gt;
      &lt;p&gt;This is a joke. In reality, mathematicians are taught that if
something is named after someone, that is a good indication that
person &lt;em&gt;didn’t&lt;/em&gt; invent that. &lt;a href=&quot;#fnref:3&quot; class=&quot;reversefootnote&quot; role=&quot;doc-backlink&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
    &lt;li id=&quot;fn:4&quot; role=&quot;doc-endnote&quot;&gt;
      &lt;p&gt;In fact, the underlying idea of the Fréchet derivative is linear
  approximations like that, Unlike partial deriviatives, this idea
  carries over to the infinite dimensional case, where it’s a stronger
  requirement than weaker notions of differentiability like the
  existence of the &lt;a href=&quot;https://en.wikipedia.org/wiki/Gateaux_derivative&quot;&gt;Gateaux derivative&lt;/a&gt;. &lt;a href=&quot;#fnref:4&quot; class=&quot;reversefootnote&quot; role=&quot;doc-backlink&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
  &lt;/ol&gt;
&lt;/div&gt;
</description>
        <pubDate>Sun, 19 Feb 2023 00:00:00 +0000</pubDate>
        <link>https://heiner.ai/blog/2023/02/19/chain-rule-jacobians-autograd-shapes.html</link>
        <guid isPermaLink="true">https://heiner.ai/blog/2023/02/19/chain-rule-jacobians-autograd-shapes.html</guid>
        
        
        <category>blog</category>
        
      </item>
    
      <item>
        <title>Gompertz, annuities, and special functions</title>
        <description>&lt;p&gt;This is part 2 of a 2 part series on Gompertz’s law. &lt;a href=&quot;/blog/2021/03/23/pis-deaths-and-statistics.html&quot;&gt;Part 1 is
here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;a href=&quot;/blog/2021/03/23/pis-deaths-and-statistics.html&quot;&gt;first part of this
series&lt;/a&gt; discussed the
Gompertz distribution and gave a formula for “How
likely am I to live until at least age \(t_0 + t\) conditional on
having lived until age \(t_0\)?”. In this post, we will use this to
compute the present value of an annuities. This is a riff on chapter 3
of &lt;a href=&quot;https://www.goodreads.com/book/show/13838804-7-most-important-equations-for-your-retirement&quot;&gt;Moshe Milevsky’s book &lt;em&gt;The 7 Most Important Equations for Your
Retirement&lt;/em&gt;&lt;/a&gt;
with a more mathy twist.&lt;/p&gt;

&lt;h3 id=&quot;present-value&quot;&gt;Present value&lt;/h3&gt;

&lt;p&gt;A standard idea in finance is that getting \(\$1000\) today is worth more
than getting \(\$1000\) in a year from now. This should be true even if
these are inflation-adjusted dollars: If we assume some bank will give
us the expected rate of inflation as their interest rate when we deposit
the \(\$1000\), we could just do that and create the “\(\$1000\) a year
from now” situation. Ignoring the dilemma of choice, the first situation
gives us more options and should therefore be worth more to us.&lt;/p&gt;

&lt;p&gt;How much more should it be worth? Or, equivalently, what’s the value
for \(y\) at which point we become ambivalent about \(\$x\) now and
\(\$y\) in one year?&lt;/p&gt;

&lt;p&gt;The answer will be different for different people (you may really need
that money &lt;em&gt;now&lt;/em&gt;), but generally this is modeled with an
interest/discount rate as well: \(\$x\) today will be worth \(\$x\cdot(1+r)\)
a year from now (and therefore \(\$x\cdot (1+r)^2\) two years from now) for some
discount rate \(r\). Why the temporal structure is exponential as
opposed to some other increasing function is a topic all for itself
(look up &lt;em&gt;hyperbolic discounting&lt;/em&gt;), but it’s a common choice in
various fields including finance, economics, psychology, neuroscience,
and reinforcement learning.&lt;/p&gt;

&lt;p&gt;Conversely, \(\$y\) in one year should be worth \(\frac{\$y}{1+r}\)
today.&lt;/p&gt;

&lt;h3 id=&quot;getting-money-forever&quot;&gt;Getting money &lt;em&gt;forever&lt;/em&gt;&lt;/h3&gt;

&lt;p&gt;A nice property of this discounting rule is that the option of getting
a neverending stream of money (say, \(a = \$1000\) every month) is worth a
finite amount today by the magic of the geometric series:&lt;/p&gt;

\[\sum_{n=0}^\infty \frac{a}{(1+r)^n} = \frac{a}{1-\frac{1}{1+r}}
= a \frac{1+r}{r} = a(1 + \tfrac{1}{r})\]

&lt;p&gt;for a monthly discount rate \(r\ne 0\). Just to be extra clear: The
\(n\)th term of this sum is the present value of the payment we
receive in the \(n\)th period.&lt;/p&gt;

&lt;p&gt;Such an arragement is called an &lt;em&gt;annuity&lt;/em&gt;. We &lt;a href=&quot;/blog/2019/08/20/annuity-loans.html&quot;&gt;talked about annuity
loans before on this blog&lt;/a&gt; and
just as in that case, the present value of a neverending stream of
\(a\) per month is \(a\) times an &lt;em&gt;annuity factor&lt;/em&gt;, in this case
\(\af(r)=1 + \frac{1}{r}\).&lt;/p&gt;

&lt;p&gt;The same is true if the annuity runs out after a fixed number of
periods. However, as a component for retirement planning, annuities
that pay for the rest of ones natural life (or the life of ones
spouse) tend to be a better option, as they
help covering &lt;em&gt;longevity risk&lt;/em&gt;. In fact, annuities are (in theory,
although maybe not psychologically in practice) a great component of a
retirement plan as they allow pensioners to take more risk with
the rest of their funds, e.g., stay invested in the stock market
where expected returns are higher (but so is the variance of returns).&lt;/p&gt;

&lt;h3 id=&quot;getting-money-until-you-die&quot;&gt;Getting money until you die&lt;/h3&gt;

&lt;p&gt;This raises a question: What’s the present value of an annuity that
pays for the rest of ones life? It ought to be less than
\(1+\frac{1}{r}\) times the annual amount (unless one expects to live
forever), but how much less exactly?&lt;/p&gt;

&lt;p&gt;Our answer, of course, is the survival function of the Gompertz
distribution, as per the &lt;a href=&quot;/blog/2021/03/23/pis-deaths-and-statistics.html#plugging-it-all-together&quot;&gt;last blog
post&lt;/a&gt;. Of
course this depends on the current age of the pensioner: The survival
function of the Gompertz distribution,
conditioned on having lived until year \(t_0\), is&lt;/p&gt;

\[p_{t_0}(t) := \exp\bigl(- e^{b(t_0-t_m)} (e^{bt} - 1)\bigr)
\where{t\ge 0}\]

&lt;p&gt;where \(b \approx 1/9.5\) is the inverse dispersion coefficient and
\(t_m \approx 87.25\) is the modal value of human life.&lt;/p&gt;

&lt;p&gt;The value of a pension that starts now (with a pensioner at age
\(t_0\)) and pays \(\$1\) per year for the rest of the life is
therefore&lt;/p&gt;

\[\af(r, t_0) =
\sum_{n=0}^\infty \frac{p_{t_0}(n)}{(1 + r)^n}.
\tag{#3} \label{discraf}\]

&lt;p&gt;The \(n\)th term in this series is the probabilty of being alive at
year \(t_0 + n\) given having been alive at year \(t_0\) times the
discount rate that turns it into a present value.&lt;/p&gt;

&lt;p&gt;This is equation #3 in Milevsky’s book &lt;em&gt;The 7 Most Important Equations
for Your Retirement&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Some insurance contracts allow the pensioner to decide between a lump
sum payment or an annuity; this formula can help to compare these two
options. Some contracts provide payments until death, but with a
minimum of (say) 10 years. Replacing \(p_{t_0}(0), \ldots,
p_{t_0}(9)\) with \(1\) in \(\eqref{discraf}\) would model this situation.&lt;/p&gt;

&lt;p&gt;Milevsky suggests using a spreadsheet program to sum this series,
along the lines of&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;\(n\)&lt;/th&gt;
      &lt;th&gt;\(p_{65}(n)\)&lt;/th&gt;
      &lt;th&gt;\((1+r)^{-n}\)&lt;/th&gt;
      &lt;th&gt;product&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;70&lt;/td&gt;
      &lt;td&gt;93.6%&lt;/td&gt;
      &lt;td&gt;0.705&lt;/td&gt;
      &lt;td&gt;0.660&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;75&lt;/td&gt;
      &lt;td&gt;83.6%&lt;/td&gt;
      &lt;td&gt;0.497&lt;/td&gt;
      &lt;td&gt;0.415&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;80&lt;/td&gt;
      &lt;td&gt;69.1%&lt;/td&gt;
      &lt;td&gt;0.35&lt;/td&gt;
      &lt;td&gt;0.242&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;85&lt;/td&gt;
      &lt;td&gt;50.0%&lt;/td&gt;
      &lt;td&gt;0.247&lt;/td&gt;
      &lt;td&gt;0.124&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;90&lt;/td&gt;
      &lt;td&gt;29.0%&lt;/td&gt;
      &lt;td&gt;0.174&lt;/td&gt;
      &lt;td&gt;0.050&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;95&lt;/td&gt;
      &lt;td&gt;11.5%&lt;/td&gt;
      &lt;td&gt;0.122&lt;/td&gt;
      &lt;td&gt;0.014&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;100&lt;/td&gt;
      &lt;td&gt;2.4%&lt;/td&gt;
      &lt;td&gt;0.086&lt;/td&gt;
      &lt;td&gt;0.002&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;105&lt;/td&gt;
      &lt;td&gt;0.2%&lt;/td&gt;
      &lt;td&gt;0.061&lt;/td&gt;
      &lt;td&gt;0.000&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt; &lt;/td&gt;
      &lt;td&gt; &lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;∑&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;1.507&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;In this example a pensioner of age 65 buys an annuity that gives them
\(\$1\) every 5 years (starting at age 70) with a discount rate of
\(r=7.25\%\). The present value of that annuity is \(\$1.51\). If the
payment every 5 years is \(\$50.000\) instead, the present value of the
annuity at age 65 is \(1.507\cdot \$50.000 = \$ 75369.90\).&lt;/p&gt;

&lt;p&gt;The example uses 5 year intervals in order to not get unduly
long. But typically, annuities will pay monthly. Computing the sum in
a spreadsheet then becomes somewhat annoying:
Here’s an &lt;a href=&quot;https://docs.google.com/spreadsheets/d/1IvtfyU9qddNthHRmai9soHpTad79aNgUU_GRnEQlukU/edit#gid=2051005501&quot;&gt;monthly example in Google
sheets&lt;/a&gt;. (Notice
that the difference to the &lt;a href=&quot;https://docs.google.com/spreadsheets/d/1IvtfyU9qddNthHRmai9soHpTad79aNgUU_GRnEQlukU/edit#gid=0&quot;&gt;5 year interval
version&lt;/a&gt;
actually matters: In the latter case, one gets the money for five
years in advance; in the former case one gets it only for the current
month. A lot can happen in 5 years.)&lt;/p&gt;

&lt;p&gt;I wasn’t quite satisfied with this.&lt;/p&gt;

&lt;h3 id=&quot;the-hunt-for-a-closed-form-solution&quot;&gt;The hunt for a closed-form solution&lt;/h3&gt;

&lt;p&gt;Equation \(\eqref{discraf}\) is nice and all, but it would be much
better to have a closed-form expression for it. Since \(p_{t_0}\) is a
doubly-exponential function, the solution isn’t immediately
obvious. In fact, I don’t know a closed-form solution for
\(\eqref{discraf}\)&lt;sup id=&quot;fnref:1&quot; role=&quot;doc-noteref&quot;&gt;&lt;a href=&quot;#fn:1&quot; class=&quot;footnote&quot; rel=&quot;footnote&quot;&gt;1&lt;/a&gt;&lt;/sup&gt;.&lt;/p&gt;

&lt;p&gt;But let’s imagine a world with continuous banking, where instead of
once a month we get a small portion of our annuity every moment. The
continuous annuity factor would then be&lt;/p&gt;

\[\af_c(r, t_0)
=
\int_0^\infty p_{t_0}(t) e^{-rt} \,dt =
\int_0^\infty \exp\bigl(-\eta(e^{bt} - 1)\bigr) e^{-rt} \,dt
\tag{G.1}
\label{contaf}\]

&lt;p&gt;where \(\eta = e^{b(t_0 - t_m)}\) as in the last blog post.&lt;sup id=&quot;fnref:2&quot; role=&quot;doc-noteref&quot;&gt;&lt;a href=&quot;#fn:2&quot; class=&quot;footnote&quot; rel=&quot;footnote&quot;&gt;2&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;

&lt;p&gt;This, too, doesn’t look super easy. In fact, it’s not solvable with
“elemantary” functions. But somewhere within the &lt;a href=&quot;https://dlmf.nist.gov/&quot;&gt;large zoo of special
functions&lt;/a&gt; there is the right one for us.&lt;/p&gt;

&lt;p&gt;In this case, &lt;a href=&quot;https://en.wikipedia.org/wiki/Gompertz_distribution&quot;&gt;Wikipedia already tells
us&lt;/a&gt; that the
moment-generating function (aka Laplace transform) of the Gompertz
distribution is&lt;/p&gt;

\[\E(e^{-tx})
=
\eta e^{\eta}\mathrm{E}_{t/b}(\eta) \where{t&amp;gt;0}\]

&lt;p&gt;with the &lt;a href=&quot;https://dlmf.nist.gov/8.19#E3&quot;&gt;generalized exponential integral&lt;/a&gt;&lt;/p&gt;

\[\mathrm{E}_{t/b}(\eta)=\int_1^\infty e^{-\eta v} v^{-t/b}\,dv \where{t&amp;gt;0}.\]

&lt;p&gt;The Gompertz distribution has the nice property that “left-truncated”
versions of itself are still Gompertz distributed (see the last blog
post for details). This is a consequence of the fact that its
survival function \(S(x) = \exp(-\eta(e^{bx}-1))\) shows up in its
pdf \(f(x) = b\eta S(x)e^{bx}\).&lt;/p&gt;

&lt;p&gt;Hence,&lt;/p&gt;

\[\E(e^{-tx}) = b\eta\int_0^\infty S(x) e^{-x(t-b)}\,dx
=
b\eta\af_c(t-b, t_0)  \where{t&amp;gt;0}.\]

&lt;p&gt;So the moment-generating function at \(t = r + b\) gives us a
closed-form for \(\eqref{contaf}\):&lt;/p&gt;

\[\af_c(r, t_0)
=
\frac{1}{b\eta}\E(e^{-(r+b)x})
=
\frac{e^{\eta}}{b} \mathrm{E}_{1+r/b}(\eta)
=
\frac{1}{b}\exp(e^{b(t_0 - t_m)})\mathrm{E}_{1+r/b}(e^{b(t_0 - t_m)}).
\label{contaf-gef}
\tag{G.2}\]

&lt;div class=&quot;centered&quot;&gt;
&lt;img src=&quot;/img/af.svg&quot; alt=&quot;pdf&quot; style=&quot;width:70%;&quot; /&gt;
&lt;br /&gt;
The annuity factor \(\af_c(r, t_0)\) for different interest rates
\(r\) and starting ages \(t_0\). Retiring early is expensive.
&lt;a href=&quot;/img/af.gp&quot;&gt;Gnuplot source&lt;/a&gt;
&lt;/div&gt;

&lt;h3 id=&quot;trying-to-use-this&quot;&gt;Trying to use this&lt;/h3&gt;

&lt;p&gt;Formula \(\eqref{contaf-gef}\) is in fact a closed-form solution to
our problem. So let’s try to use it in a computation with
Python. &lt;a href=&quot;https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.expn.html&quot;&gt;SciPy has the generalized exponential integral
function&lt;/a&gt;,
so this should be easy:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;scipy&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;special&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;9.5&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;t_m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;87.25&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;af&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;r&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t_0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t_0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t_m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;special&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;expn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;r&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;af&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.025&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t_0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;65&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;and the output is:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;gompertz_discount.py:10: RuntimeWarning: floating point number truncated to an integer
  return np.exp(eta) / b * special.expn(1 + r / b, eta)
19.439804660538815
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Ah, dang! Even though the generalized exponential function is part of
SciPy, the implementation there only supports integer orders.&lt;/p&gt;

&lt;p&gt;We’ll have to visit the special functions zoo for a bit longer.&lt;/p&gt;

&lt;h4 id=&quot;more-zoo-animals-the-incomplete-gamma-function&quot;&gt;More zoo animals: The incomplete gamma function&lt;/h4&gt;

&lt;p&gt;The classic reference for special functions is &lt;a href=&quot;https://en.wikipedia.org/wiki/Abramowitz_and_Stegun&quot;&gt;Abramowitz and
Stegun&lt;/a&gt;. Wikipedia
has a quote about it from the (American) National Institute of
Standards and Technology:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;More than 1,000 pages long, the Handbook of Mathematical Functions
was first published in 1964 and reprinted many times […] [W]hen
New Scientist magazine
recently asked some of the world’s leading scientists what single
book they would want if stranded on a desert island, one
distinguished British physicist said he would take the
Handbook. […] During the mid-1990s, the book was cited every 1.5
hours of each working day.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In the internet age, the &lt;a href=&quot;https://dlmf.nist.gov/&quot;&gt;Digital Library of Mathematical Functions
(DLMF)&lt;/a&gt; hosts an updated version of this
classic work and it is very useful for situations like the one we are
in now.&lt;/p&gt;

&lt;p&gt;In fact, looking at &lt;a href=&quot;https://dlmf.nist.gov/8.19#E1&quot;&gt;equation 8.19.1&lt;/a&gt;
in DLMF, we see that the generalized exponential integral is nothing
but the (upper) incomplete gamma function:&lt;/p&gt;

\[\mathrm{E}_p(z) = z^{p-1}\Gamma(1-p, z)  \where{p, z\in\C}\]

&lt;p&gt;and thus&lt;/p&gt;

\[\af_c(r, t_0)
=
\frac{e^{\eta}}{b} \mathrm{E}_{1+r/b}(\eta)
=
\frac{\eta^{r/b}e^{\eta}}{b} \Gamma(-r/b, \eta).\]

&lt;p&gt;Alas, this won’t do either. &lt;a href=&quot;https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.gammaincc.html&quot;&gt;SciPy’s implementation of the incomplete
gamma
function&lt;/a&gt;
doesn’t allow for a negative first argument.&lt;/p&gt;

&lt;p&gt;Why might this be the case? Looking at the definition of the
incomplete gamma functions in DLMF (&lt;a href=&quot;https://dlmf.nist.gov/8.2#E2&quot;&gt;8.2.2
there&lt;/a&gt;), we read&lt;/p&gt;

\[\Gamma(a, z) = \int_z^\infty t^{a-1}e^{-t}\,dt  \where{a, z\in\C, \
\Re a &amp;gt; 0}.\]

&lt;p&gt;Note how this is an “incomplete” version of the standard gamma
function \(\Gamma(a) = \Gamma(a, 0)\). Also note how this integral
won’t work for negative \(a\): There’s a non-integrable singularity
when \(z=0\).&lt;/p&gt;

&lt;p&gt;So did our previous formulae not make any sense? They did. We just
have to understand these functions a little bit better.&lt;/p&gt;

&lt;h3 id=&quot;analytic-continuation&quot;&gt;Analytic continuation&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Complex analysis&lt;/em&gt;, the theory of differentiable complex functions, is
one of the most beautiful areas of mathematics. In fact, I believe I
once saw a video of Donald Knuth saying it’s such a great topic that
he asked his daughter to attend a complex analysis course – although
she didn’t otherwise study at any university.&lt;sup id=&quot;fnref:3&quot; role=&quot;doc-noteref&quot;&gt;&lt;a href=&quot;#fn:3&quot; class=&quot;footnote&quot; rel=&quot;footnote&quot;&gt;3&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;

&lt;p&gt;One of the results of complex analysis is that if two nice
(aka complex-differentiable, aka holomorphic, aka analytic) functions
coincide on a set that’s not totally discrete, they &lt;a href=&quot;https://en.wikipedia.org/wiki/Identity_theorem&quot;&gt;are the
same&lt;/a&gt;! This means any
analytic function like \(a\mapsto\Gamma(a, z)\) has at most one
analytic continuation. This is an important principle which also
applies to the famous Riemann zeta function \(\zeta\). The zeros of
its analytic continuation to the left complex half-plane
are what the &lt;a href=&quot;https://en.wikipedia.org/wiki/Riemann_hypothesis&quot;&gt;most important open problem in mathematics is
about&lt;/a&gt; (you’ll get
&lt;a href=&quot;https://www.claymath.org/millennium-problems/riemann-hypothesis&quot;&gt;$1M if you solve this
one&lt;/a&gt;,
which should help with retirement planning). In fact, \(\zeta\) and
\(\Gamma\) are closely linked.&lt;/p&gt;

&lt;p&gt;In the case of \(\zeta(s) := \sum_{n=1}^\infty n^{-s}\) its unique
analytic continuation to the left half-plane yields for
instance \(\zeta(-1) = -\frac{1}{12}\) which gives some sense to
Ramanujan’s mysterious
equation \(1 + 2 + 3 + \cdots = -\frac{1}{12}.\)&lt;/p&gt;

&lt;p&gt;How is such an analytic continuation found? In the case of both
the zeta and the gamma functions, it’s via functional equations. For
instance, \(\Gamma(n) = (n-1)!\) for integer \(n\), and more generally
\(\Gamma(z+1) = z\Gamma(z)\) for complex \(z\). If we start with some
\(z\) in the left
half-plane (i.e., \(\Im z \le 0\)), repeatedly applying this formula
eventually yields only terms of \(\Gamma\) at “known” arguments, which
establishes the value of the analytic continuation of \(\Gamma\) to
that point \(z\).&lt;/p&gt;

&lt;p&gt;For the incomplete Gamma function, a similar recurrence relation
exists, namely (&lt;a href=&quot;https://dlmf.nist.gov/8.8#E2&quot;&gt;8.8.2&lt;/a&gt; in DLMF)&lt;/p&gt;

\[\Gamma(a+1, z) = a\Gamma(a,z) + z^ae^{-z}\]

&lt;p&gt;for, say, \(a\) and \(z\) in the right half-plane. This equation can be
used to extend the incomplete gamma function to negative values of
\(a\). It also gives rise to a corresponding recurrence relation for the
generalized exponential integral
(&lt;a href=&quot;https://dlmf.nist.gov/8.19#E12&quot;&gt;8.19.12&lt;/a&gt; in DLMF)&lt;/p&gt;

\[p\mathrm{E}_{p+1}(z) + z\mathrm{E}_{p}(z) = e^{-z}.\]

&lt;h3 id=&quot;applying-the-functional-equation&quot;&gt;Applying the functional equation&lt;/h3&gt;

&lt;p&gt;Since the implementations of \(\mathrm{E}_{p}(z)\) and \(\Gamma(a,z)\)
that we want to use don’t implement the continued versions of
these functions, we can use the functional equations that define the
continuations ourselves. The recurrence relation for
\(\mathrm{E}_{p+1}\) yields&lt;/p&gt;

\[\begin{align}
\af_c(r, t_0)
&amp;amp; =
\frac{e^{\eta}}{b} \mathrm{E}_{1+r/b}(\eta)
=
\frac{e^{\eta}}{r}\bigl(e^{-\eta} - \eta\mathrm{E}_{r/b}(\eta)\bigr)
= \frac{1}{r}\bigl(1 - \eta e^\eta\mathrm{E}_{r/b}(\eta)\bigr)
\\
&amp;amp; = \frac{1}{r}\bigl(1 - e^\eta \eta^{r/b} \Gamma(1 - r/b, \eta)\bigr).
\end{align}\]

&lt;p&gt;For moderate values of \(r\) (and \(b\)), this is enough. For very
large \(r\) we’d have to apply the recurrence relation again.&lt;/p&gt;

&lt;p&gt;This allows us to finally run this in Python:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;scipy&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;special&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;9.5&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;t_m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;87.25&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;af&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;r&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t_0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t_0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t_m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
        &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
        &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;r&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;special&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;r&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;special&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gammaincc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;r&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# A normalized version of \Gamma(a, z).
&lt;/span&gt;    &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;r&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;af&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.025&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t_0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;65&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Which prints &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;14.79901377449508&lt;/code&gt;.&lt;/p&gt;

&lt;h4 id=&quot;what-about-spreadsheets&quot;&gt;What about spreadsheets?&lt;/h4&gt;

&lt;p&gt;The above works for SciPy, but Excel (or Google Sheets) is a different
matter as it doesn’t directly have support for the incomplete gamma
function.&lt;sup id=&quot;fnref:4&quot; role=&quot;doc-noteref&quot;&gt;&lt;a href=&quot;#fn:4&quot; class=&quot;footnote&quot; rel=&quot;footnote&quot;&gt;4&lt;/a&gt;&lt;/sup&gt; However, it does support the &lt;a href=&quot;https://en.wikipedia.org/wiki/Gamma_distribution&quot;&gt;Gamma
distribution&lt;/a&gt; which
has a normalized version of the lower incomplete gamma function as
its cdf. As the helpful authors of &lt;a href=&quot;https://en.wikipedia.org/wiki/Incomplete_gamma_function#Software_Implementation&quot;&gt;Wikipedia
note&lt;/a&gt;,
\(\Gamma(s, x)\) can be computed as
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;GAMMA(s)*(1-GAMMA.DIST(x,s,1,TRUE))&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This finally gives us closed-form we can use in spreadsheets. &lt;a href=&quot;https://docs.google.com/spreadsheets/d/1IvtfyU9qddNthHRmai9soHpTad79aNgUU_GRnEQlukU/edit#gid=1825725391&quot;&gt;Here’s
an example in Google
Sheets&lt;/a&gt;.
Note that the relative difference of \(\af(r,t_0)\) and
\(\af_c(r,t_0)\) for \(r = 0.25\%\) and \(t_0 = 65\) is only
\(0.64\%\).&lt;/p&gt;

&lt;h3 id=&quot;what-does-it-all-mean&quot;&gt;What does it all mean?&lt;/h3&gt;

&lt;p&gt;If you (or your parents) bought an annuity in your name and the issuer
offers the option for a lump sum payment instead, you can multiply the
yearly (or monthly) payments with the annuity factor as determined
above, treat that as the annuity’s value, and compare it to the lump
sum. (The computations here mostly assume the annuity will start right
away, extending this to an annuity that starts in a number of years is
left as an exercise for the reader.)&lt;/p&gt;

&lt;p&gt;That raises the question of which interest rate to pick? And why that
should be treated as constant over time?&lt;/p&gt;

&lt;p&gt;Also, the annuity provider will have done some math as well and will be
aware of &lt;em&gt;adverse selection&lt;/em&gt;: People who self-assess as being in good
health might be right about this and choose the annuity more
often. Milevsky quotes from Jane Austen’s &lt;em&gt;Sense and Sensibility&lt;/em&gt;,&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;People always live forever when there is an annuity to be paid them.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Milevsky also ends his discussion of his equation #3 with a warning:
This is a model. If market prices are different, they are likely to be
right and the model wrong.&lt;/p&gt;

&lt;p&gt;That said, &lt;em&gt;if&lt;/em&gt; you got an annuity a while back, for instance pre-2008
when the &lt;a href=&quot;https://fred.stlouisfed.org/series/FEDFUNDS&quot;&gt;effective Fed funds rate was
5%+&lt;/a&gt;, you likely got a
good deal by today’s standards. The future might be different. But at
least some people argue that interest rates will stay permanentely
low, as they did in Japan for the last decades (demographic factors
might play a role here). Others disagree, and of course people some
always predict stronger inflation.&lt;/p&gt;

&lt;p&gt;That’s it for today, thanks for reading. Reach out if you have
comments.&lt;/p&gt;
&lt;div class=&quot;footnotes&quot; role=&quot;doc-endnotes&quot;&gt;
  &lt;ol&gt;
    &lt;li id=&quot;fn:1&quot; role=&quot;doc-endnote&quot;&gt;
      &lt;p&gt;Although coming to think of this perhaps
&lt;a href=&quot;https://en.wikipedia.org/wiki/Abel%E2%80%93Plana_formula&quot;&gt;Abel-Plana&lt;/a&gt;
might help? Eyeballing our function \(f(z) =
p_{t_0}(z)e^{-z\ln(1+r)}\) it might apply, but the \(\int_0^\infty
\frac{f(iy) - f(-iy)}{e^{2\pi y} - 1}\,dy\) integral looks &lt;em&gt;hard&lt;/em&gt;. &lt;a href=&quot;#fnref:1&quot; class=&quot;reversefootnote&quot; role=&quot;doc-backlink&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
    &lt;li id=&quot;fn:2&quot; role=&quot;doc-endnote&quot;&gt;
      &lt;p&gt;There’s some extra confusion regarding the interest rate here:
For continuous compounding we need something else than the
effective rate, as \(e^r - 1 \ne r\) for \(r &amp;gt; 0\). See &lt;a href=&quot;https://math.stackexchange.com/a/4099424/5051&quot;&gt;this
answer&lt;/a&gt; for some
explanation. &lt;a href=&quot;#fnref:2&quot; class=&quot;reversefootnote&quot; role=&quot;doc-backlink&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
    &lt;li id=&quot;fn:3&quot; role=&quot;doc-endnote&quot;&gt;
      &lt;p&gt;I might misremember this; at any rate I can’t find the reference
right now. It might have been part of his &lt;a href=&quot;https://www.youtube.com/watch?v=mert0kmZvVM&quot;&gt;1987 course series on
mathematical writing&lt;/a&gt;. &lt;a href=&quot;#fnref:3&quot; class=&quot;reversefootnote&quot; role=&quot;doc-backlink&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
    &lt;li id=&quot;fn:4&quot; role=&quot;doc-endnote&quot;&gt;
      &lt;p&gt;Apparently, &lt;a href=&quot;https://support.microsoft.com/en-us/office/gamma-function-ce1702b1-cf55-471d-8307-f83be0fc5297&quot;&gt;Microsoft Excel supports &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Gamma&lt;/code&gt; at negative
values&lt;/a&gt;. However,
&lt;a href=&quot;https://support.google.com/docs/answer/9365856?hl=en&quot;&gt;Google
Sheets&lt;/a&gt;
doesn’t. For Excel, we could have also used a series like &lt;a href=&quot;https://dlmf.nist.gov/8.7#E3&quot;&gt;8.7.3 in
DLMF&lt;/a&gt; to compute the incomplete
gamma function. &lt;a href=&quot;#fnref:4&quot; class=&quot;reversefootnote&quot; role=&quot;doc-backlink&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
  &lt;/ol&gt;
&lt;/div&gt;
</description>
        <pubDate>Wed, 14 Apr 2021 00:00:00 +0000</pubDate>
        <link>https://heiner.ai/blog/2021/04/14/gompertz-annuities-and-special-functions.html</link>
        <guid isPermaLink="true">https://heiner.ai/blog/2021/04/14/gompertz-annuities-and-special-functions.html</guid>
        
        
        <category>blog</category>
        
      </item>
    
      <item>
        <title>πs, deaths, and statistics</title>
        <description>&lt;p&gt;This is part 1 of a 2 part series on Gompertz’s law.&lt;/p&gt;

&lt;p&gt;After enjoying a &lt;a href=&quot;https://rationalreminder.ca/podcast/122&quot;&gt;podcast interviewing Moshe
Milevsky&lt;/a&gt;, I got interested
in Milevsky’s work and read his book &lt;em&gt;The 7 Most Important Equations for Your
Retirement&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;It’s a bit of a weird book. I can’t say I didn’t enjoy it. But it
gave me the impression Moshe Milevsky didn’t expect his readers to enjoy the
book, or at least he didn’t seem to expect them to like the formulas. That
seems like a weird proposition for a book with “equations” in its
very title. Perhaps the readers were imagined to be part of a
captured audience of students, asked to read the book as an
assignment? At any rate the author apologizes every time he actually
discusses formulae, and having to resort to &lt;em&gt;logarithms&lt;/em&gt; seems to make
him positively embarrassed.&lt;/p&gt;

&lt;p&gt;Then again, Prof. Milevsky wrote many books and this is apparently one
of his bestsellers. And
the anecdotes of Fibonacci, Gompertz, Halley, Fisher, Huebner, and
Kolmogorov&lt;sup id=&quot;fnref:1&quot; role=&quot;doc-noteref&quot;&gt;&lt;a href=&quot;#fn:1&quot; class=&quot;footnote&quot; rel=&quot;footnote&quot;&gt;1&lt;/a&gt;&lt;/sup&gt; in the book are lovely, as is Milevsky’s account of his
experience of economist Paul Samuelson. Perhaps the professor just
knows his audience.&lt;/p&gt;

&lt;p&gt;But so do I, being well acquainted with the empty set. So there’s no
issue with too much math on this blog.&lt;/p&gt;

&lt;p&gt;Let’s therefore discuss what Milevsky doesn’t do in his book and try
to explain why his equation #2 might be true: Let’s talk about the
Gompertz distribution.&lt;/p&gt;

&lt;h3 id=&quot;gompertzs-discovery&quot;&gt;Gompertz’s discovery&lt;/h3&gt;

&lt;div class=&quot;floated&quot;&gt;
&lt;img src=&quot;/img/gompertz.png&quot; alt=&quot;Benjamin Gompertz&quot; style=&quot;width:200px;&quot; /&gt;
&lt;br /&gt;
&lt;div class=&quot;centered small&quot;&gt;
Image source: &lt;a href=&quot;https://en.wikipedia.org/wiki/Benjamin_Gompertz#/media/File:Gompertz.png&quot;&gt;Wikipedia&lt;/a&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Benjamin Gompertz (1779–1865) was a British mathematician and actuary
of German Jewish descent. According to Milevsky, Gompertz was looking
for a law of human mortality, comparable to Newton’s laws of
mechanics. At his time, statistics of people’s lifespan were already
available and formed the basis for Gompertz’s discovery. For instance,
one could compile a &lt;em&gt;mortality table&lt;/em&gt; of a (hypothetical) group of
45-year-olds as they age. The data might look like this:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Age&lt;/th&gt;
      &lt;th&gt;Alive at Birthday&lt;/th&gt;
      &lt;th&gt;Die in Year&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;45&lt;/td&gt;
      &lt;td&gt;98,585&lt;/td&gt;
      &lt;td&gt;146&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;46&lt;/td&gt;
      &lt;td&gt;98,439&lt;/td&gt;
      &lt;td&gt;161&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;47&lt;/td&gt;
      &lt;td&gt;98,278&lt;/td&gt;
      &lt;td&gt;177&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;48&lt;/td&gt;
      &lt;td&gt;98,101&lt;/td&gt;
      &lt;td&gt;195&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;49&lt;/td&gt;
      &lt;td&gt;97,906&lt;/td&gt;
      &lt;td&gt;214&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;50&lt;/td&gt;
      &lt;td&gt;97,692&lt;/td&gt;
      &lt;td&gt;236&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;What does this tell us? It doesn’t immediately tell &lt;em&gt;me&lt;/em&gt; anything not
very obvious: The older one gets, the more likely one dies soon.&lt;/p&gt;

&lt;p&gt;But let’s
compute the &lt;em&gt;mortality rate&lt;/em&gt;: How likely were people to die at a given
age in this cohort? To be precise, we compute “&lt;em&gt;Which proportion of
people alive at age \(t\) died before age \(t+1\)?”&lt;/em&gt;&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Age&lt;/th&gt;
      &lt;th&gt;Alive at Birthday&lt;/th&gt;
      &lt;th&gt;Die in Year&lt;/th&gt;
      &lt;th&gt;Mortality Rate&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;45&lt;/td&gt;
      &lt;td&gt;98,585&lt;/td&gt;
      &lt;td&gt;146&lt;/td&gt;
      &lt;td&gt;0.148%&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;46&lt;/td&gt;
      &lt;td&gt;98,439&lt;/td&gt;
      &lt;td&gt;161&lt;/td&gt;
      &lt;td&gt;0.164%&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;47&lt;/td&gt;
      &lt;td&gt;98,278&lt;/td&gt;
      &lt;td&gt;177&lt;/td&gt;
      &lt;td&gt;0.180%&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;48&lt;/td&gt;
      &lt;td&gt;98,101&lt;/td&gt;
      &lt;td&gt;195&lt;/td&gt;
      &lt;td&gt;0.199%&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;49&lt;/td&gt;
      &lt;td&gt;97,906&lt;/td&gt;
      &lt;td&gt;214&lt;/td&gt;
      &lt;td&gt;0.219%&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;50&lt;/td&gt;
      &lt;td&gt;97,692&lt;/td&gt;
      &lt;td&gt;236&lt;/td&gt;
      &lt;td&gt;0.242%&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;So again, so much so obvious: The probability of dying the next year,
conditional on having lived until the current year,
increases with age.&lt;/p&gt;

&lt;p&gt;But &lt;em&gt;how much&lt;/em&gt; does it increase? This is
Gompertz’s discovery, now called Gompertz’s law: The mortality rate
appears to increase exponentially. One way of seeing this is to take
logs and compute their difference:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Age&lt;/th&gt;
      &lt;th&gt;Alive at Birthday&lt;/th&gt;
      &lt;th&gt;Die in Year&lt;/th&gt;
      &lt;th&gt;Mortality Rate&lt;/th&gt;
      &lt;th&gt;Log of Mortality Rate&lt;/th&gt;
      &lt;th&gt;Difference in Log Values&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;45&lt;/td&gt;
      &lt;td&gt;98,585&lt;/td&gt;
      &lt;td&gt;146&lt;/td&gt;
      &lt;td&gt;0.148%&lt;/td&gt;
      &lt;td&gt;−6.515&lt;/td&gt;
      &lt;td&gt;—&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;46&lt;/td&gt;
      &lt;td&gt;98,439&lt;/td&gt;
      &lt;td&gt;161&lt;/td&gt;
      &lt;td&gt;0.164%&lt;/td&gt;
      &lt;td&gt;−6.416&lt;/td&gt;
      &lt;td&gt;0.0993&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;47&lt;/td&gt;
      &lt;td&gt;98,278&lt;/td&gt;
      &lt;td&gt;177&lt;/td&gt;
      &lt;td&gt;0.180%&lt;/td&gt;
      &lt;td&gt;−6.319&lt;/td&gt;
      &lt;td&gt;0.0964&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;48&lt;/td&gt;
      &lt;td&gt;98,101&lt;/td&gt;
      &lt;td&gt;195&lt;/td&gt;
      &lt;td&gt;0.199%&lt;/td&gt;
      &lt;td&gt;−6.221&lt;/td&gt;
      &lt;td&gt;0.0987&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;49&lt;/td&gt;
      &lt;td&gt;97,906&lt;/td&gt;
      &lt;td&gt;214&lt;/td&gt;
      &lt;td&gt;0.219%&lt;/td&gt;
      &lt;td&gt;−6.126&lt;/td&gt;
      &lt;td&gt;0.0950&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;50&lt;/td&gt;
      &lt;td&gt;97,692&lt;/td&gt;
      &lt;td&gt;236&lt;/td&gt;
      &lt;td&gt;0.242%&lt;/td&gt;
      &lt;td&gt;−6.026&lt;/td&gt;
      &lt;td&gt;0.1000&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;The difference in log values increases by about 0.1, regardless of the
current age. Since \(\exp(0.1) \approx 1.1\), this works out to
roughly a 10% increase in the mortality rate per year.&lt;/p&gt;

&lt;p&gt;&lt;b&gt;According to Gompertz’s discovery, the likelihood of dying in the
next year (conditional on having lived until this year) increases
exponentially by a fixed percentage every year.&lt;b&gt;&lt;/b&gt;&lt;/b&gt;&lt;/p&gt;

&lt;p&gt;How do we model this mathematically? And if Gompertz’s law has a
rate growing by a rate, how come everything stays a probability, i.e.,
\(\le 1\)?&lt;/p&gt;

&lt;p&gt;Keep reading to learn about hazard functions and find out!&lt;/p&gt;

&lt;h3 id=&quot;pdfs-cdfs-and-hazard-functions&quot;&gt;PDFs, CDFs, and Hazard Functions&lt;/h3&gt;

&lt;div class=&quot;floated&quot;&gt;
&lt;img src=&quot;/img/gompertz-pdf.svg&quot; alt=&quot;pdf&quot; style=&quot;width:250px;&quot; /&gt;
&lt;br /&gt;
&lt;div class=&quot;centered small&quot;&gt;
Some probability density functions&lt;br /&gt;
Image source: &lt;a href=&quot;https://en.wikipedia.org/wiki/File:GompertzPDF.svg&quot;&gt;Wikipedia&lt;/a&gt;
&lt;/div&gt;
&lt;img src=&quot;/img/gompertz-cdf.svg&quot; alt=&quot;cdf&quot; style=&quot;width:250px;&quot; /&gt;
&lt;br /&gt;
&lt;div class=&quot;centered small&quot;&gt;
Some cumulative distribution functions&lt;br /&gt;
Image source: &lt;a href=&quot;https://en.wikipedia.org/wiki/File:GompertzCDF.svg&quot;&gt;Wikipedia&lt;/a&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;If you have taken a probability or statistics course, you probably
(ha!) know about &lt;em&gt;probability density functions&lt;/em&gt; (pdfs). A pdf is a
positive function that we use as a density and to make it a
&lt;em&gt;probabilty&lt;/em&gt; density it needs to integrate to one. If \(f\)
is a pdf and \(X\) is a random variable with that distribution then&lt;/p&gt;

\[\P(a &amp;lt; X\le b) = \int_a^b f(x) \dx,\]

&lt;p&gt;i.e., the probability of \(X\) landing between \(a\) and \(b\) is the
integral from \(a\) to \(b\) of \(f\).&lt;sup id=&quot;fnref:2&quot; role=&quot;doc-noteref&quot;&gt;&lt;a href=&quot;#fn:2&quot; class=&quot;footnote&quot; rel=&quot;footnote&quot;&gt;2&lt;/a&gt;&lt;/sup&gt; Let’s say our random
variable takes only positive values, then for \(a=0\) and \(b=\infty\)
this value will be \(1\), i.e., 100%. For smaller values of \(b\) this
will be the so-called cumulative distribution function (cdf):&lt;/p&gt;

\[F(b) := \P(X\le b) = \int_0^b f(x)\dx.\]

&lt;p&gt;While pdfs are positive and integrate to \(1\), cdfs are positive, \(0\)
at \(0\), monotone (non-decreasing), and \(1\) at the limit to
\(\infty\). They are also typically assumed to be
right-continuous. To compute the previous expression one can then
take&lt;/p&gt;

\[\P(a &amp;lt; X \le b) = \int_a^b f(x) \dx = F(b) - F(a).\]

&lt;p&gt;Moreover the fundamental theorem of calculus tells us that (barring a
few exceptional points),&lt;/p&gt;

\[F&apos;(x) = f(x).\]

&lt;p&gt;What this means is that the cdf determines the pdf and therefore the
probability distribution itself: Any function \(F\) with the properties
above can serve as a cdf and gives rise to a pdf \(f\), and vice
versa.&lt;/p&gt;

&lt;p&gt;If you made it this far, you likely knew this in principle. So on to
hazard functions now (which I learned about from
&lt;a href=&quot;https://en.wikipedia.org/wiki/Survival_analysis#Hazard_function_and_cumulative_hazard_function&quot;&gt;Wikipedia&lt;/a&gt;
only recently).&lt;/p&gt;

&lt;h4 id=&quot;hazard-functions&quot;&gt;Hazard functions&lt;/h4&gt;

&lt;div class=&quot;floated&quot;&gt;
&lt;img src=&quot;/img/gompertz-hazard.svg&quot; alt=&quot;hazard&quot; style=&quot;width:250px;&quot; /&gt;
&lt;br /&gt;
&lt;div class=&quot;centered small&quot;&gt;
Some hazard functions&lt;br /&gt;
&lt;a href=&quot;/img/gompertz.gp&quot;&gt;Gnuplot source&lt;/a&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;If we imagine \(f\) to describe deaths (or failure rates) over time,
\(F(t)\) will be the probability to have died by time
\(t\). Conversely, \(S(t) := 1 - F(t)\) (the &lt;em&gt;survival function&lt;/em&gt;) is
the chance to still be alive at time \(t\). If \(f\) is the
corresponding pdf and \(X\) is a random variable with this
distribution,&lt;/p&gt;

\[S(t) = \P(X &amp;gt; t) = \int_t^\infty f(x)\dx = 1 - F(t).\]

&lt;p&gt;Suppose we made it until some time \(t_0 \ge 0\). How will the future
look like? We will need to condition on having lived so far and
renormalize with \(S(t_0)\) to get the conditional pdf going forward,
e.g., \(f_{t_0}(t) = f(t_0 + t) / S(t_0)\).&lt;/p&gt;

&lt;p&gt;If we evaluate this truncated and renormalized pdf at \(t=0\) as a
function of \(t_0\), we get the probability of not surviving an
additional infinitesimal time (the &lt;em&gt;instantaneous rate of dying&lt;/em&gt; for
someone currently alive at age \(t_0\))​:&lt;/p&gt;

\[h(t_0) := \frac{f(t_0)}{S(t_0)}
  = \lim_{t\downarrow 0} \frac{\P(t_0\le X &amp;lt; t_0 + t)}{t S(t_0)}
  = -\frac{S&apos;(t_0)}{S(t_0)} = - \frac{\d}{\d t}\ln(S(t))\Biggr\rvert_{t=t_0}.\]

&lt;p&gt;This is the &lt;em&gt;hazard function&lt;/em&gt;, also known as &lt;em&gt;force of mortality&lt;/em&gt; or
&lt;em&gt;force of failure&lt;/em&gt;. It takes positive values and the last equation
indicates that it will not be integrable, i.e., \(\int_0^\infty
h(x)\dx = \infty\).&lt;/p&gt;

&lt;p&gt;There is also the &lt;em&gt;cumulative hazard function&lt;/em&gt;, which is&lt;/p&gt;

\[H(t) = \int_0^t h(x)\dx = -\ln S(t).\]

&lt;p&gt;This last equation, which follows from the above, tells us something
interesting: We ought to be able to retrieve \(S\), and therefore the cdf
\(F\), and therefore the pdf \(f\), from \(h\) itself, because&lt;/p&gt;

\[S(t) = e^{-H(t)}.\]

&lt;p&gt;This means, just as any one of a pdf or a cdf determines the other, so
does a hazard function: Given either a pdf, a cdf, or a hazard
function (or a cumulative hazard function), the probability density and
therefore all of these functions and the entire distribution are
uniquely determined. The criteria
for \(h\) are: (1) being nonnegative and (2) not being integrable.&lt;/p&gt;

&lt;h3 id=&quot;back-to-gompertz&quot;&gt;Back to Gompertz&lt;/h3&gt;

&lt;p&gt;So how do we model Gompertz’s discovery? We choose the most
simple exponentially growing function we know and take it as our hazard
function:&lt;/p&gt;

\[h(t) := b \eta e^{bt}\]

&lt;p&gt;where \(\eta, b &amp;gt; 0\) are parameters to be determined from the
data (see below). This also tells us why our “rate increase of a rate”
doesn’t lead to probabilities greater than one over time: The hazard
function grows to infinity and is not a pdf. However, for any \(t_0
\ge 0\), the initial value of the conditional pdf (“going forward”) is
\(h(t_0)\). For large \(t_0\), the conditional pdf starts high and
then declines rapidly; the density functions have likelihoods larger than
one but over shorter and shorter time intervals.&lt;/p&gt;

&lt;p&gt;Given this, what is the cdf for this &lt;em&gt;Gompertz distribution&lt;/em&gt;? Well,&lt;/p&gt;

\[H(t) = \int_0^t h(x)\dx = b \eta\int_0^t e^{bx}\dx
  = \eta(e^{bt} - 1)\]

&lt;p&gt;and therefore&lt;/p&gt;

\[F(t) = 1 - S(t) = 1 - e^{-H(t)} = 1 - \exp\bigl(-\eta(e^{bt} -
1)\bigr)\]

&lt;p&gt;and&lt;/p&gt;

\[f(t) = h(t)S(t) = b\eta\exp\bigl(bt - \eta(e^{bt} - 1)\bigr).\]

&lt;p&gt;So the simple exponential choice for the hazard function yields this not
quite so simple double exponential as a pdf for the Gompertz
distribution.&lt;/p&gt;

&lt;div class=&quot;centered&quot;&gt;
&lt;img src=&quot;/img/gompertz-pdf.svg&quot; alt=&quot;pdf&quot; style=&quot;width:30%;&quot; /&gt;
&lt;img src=&quot;/img/gompertz-cdf.svg&quot; alt=&quot;cdf&quot; style=&quot;width:30%;&quot; /&gt;
&lt;img src=&quot;/img/gompertz-hazard.svg&quot; alt=&quot;hazard&quot; style=&quot;width:30%;&quot; /&gt;
&lt;br /&gt;
The pdf, cdf and hazard function of the Gompertz distribution for some
choices of \(\eta\) and \(b\). &lt;br /&gt;
(See above for source.)
&lt;/div&gt;

&lt;p&gt;We could proceed to compute the mean, variance or
moment-generating function (aka Laplace transform) of this
distribution, but the math gets somewhat hairy and special functions
(mainly the &lt;a href=&quot;https://dlmf.nist.gov/8.19&quot;&gt;generalized exponential
integral&lt;/a&gt;, a special function related to
the incomplete gamma function) are involved. We
will return to this for other reasons in a future blogpost. The
&lt;a href=&quot;https://en.wikipedia.org/wiki/Gompertz_distribution&quot;&gt;infobox on
Wikipedia&lt;/a&gt; has
the data if necessary.&lt;/p&gt;

&lt;p&gt;For now, let’s note that \(h(t) = b \eta e^{bt}\) describes a hazard
function where the chance of dying in the next moment increases
throughout life, but there’s only this time-dependent component. If
there are time-independent causes of death or failure (war, some kinds of
diseases, voltage surges), one could consider modelling this
differently. William Makeham, another British 19th century
mathematician, proposed such an addition via the hazard function&lt;/p&gt;

\[h(t) = b \eta e^{bt} + \lambda.\]

&lt;p&gt;The result is known as the &lt;a href=&quot;https://en.wikipedia.org/wiki/Gompertz%E2%80%93Makeham_law_of_mortality&quot;&gt;Gompertz-Makeham
distribution&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;As simple as this change may seem, it does complicate the resulting
integrals quite a bit. So much so that finding closed-form expressions
of the &lt;a href=&quot;https://dl.acm.org/doi/abs/10.1016/j.matcom.2009.02.002&quot;&gt;quantile
function&lt;/a&gt; or
the &lt;a href=&quot;https://www.researchgate.net/publication/261641522_On_Order_Statistics_from_the_Gompertz-Makeham_Distribution_and_the_Lambert_W_Function&quot;&gt;moments of this
distribution&lt;/a&gt;
is still an active field of research!&lt;/p&gt;

&lt;h4 id=&quot;gompertz-from-here-on-out&quot;&gt;Gompertz from here on out&lt;/h4&gt;

&lt;p&gt;If a random variable \(X \sim \textrm{Gompertz}(\eta, b)\) models
the age at death of a newborn (or, less morbidly, the
time to failure for a newly built device), how does the world
look like at time \(t_0\)? That’s an important question for,
e.g., retirement planning.&lt;/p&gt;

&lt;p&gt;So let’s compute the pdf after surviving until \(t_0\):&lt;/p&gt;

\[f_{t_0}(t) = \frac{f(t_0 + t)}{S(t_0)} = b\eta\frac{\exp\bigl(b(t_0+t) -
\eta(e^{b(t_0+t)} - 1)\bigr)}{\exp\bigl(-\eta(e^{bt_0} - 1)\bigr)}
= b\eta e^{bt_0}\exp\bigl(-\eta e^{bt_0}(e^{bt}-1) + bt\bigr).\]

&lt;p&gt;This is the pdf of \(\textrm{Gompertz}(\eta e^{bt_0}, b)\). So the
future stays Gompertz-distributed with new parameters. This is a
useful property of the Gompertz distribution: truncated
renormalized versions of it stay within the family, in contrast to,
e.g., the Gaussian distribution.&lt;/p&gt;

&lt;p&gt;This helps us answer questions like “How long will I spend in
retirement?”, which is why Milevsky discusses Gompertz in his book
about retirement planning.&lt;/p&gt;

&lt;p&gt;Before we can do that, let’s discuss how one could fit the parameters
\(\eta\) and \(b\).&lt;/p&gt;

&lt;h4 id=&quot;how-to-fit-the-data-modal-value-of-human-life&quot;&gt;How to fit the data: Modal value of human life&lt;/h4&gt;

&lt;p&gt;The modal value(s) of a distribution is the maximum (or set of maxima)
of the pdf. In general, it is distinct from both the mean as well as the
median. In the case of Gompertz it’s also an easy
computation:&lt;/p&gt;

\[\frac{\d}{\d t}f(t) = 0
\ \Rightarrow\
b\eta\exp\bigl(bt - \eta(e^{bt} - 1)\bigr)(b - \eta b e^{bt}) = 0
\ \Rightarrow\
\eta e^{bt} = 1\]

&lt;p&gt;and therefore \(\eta = e^{-bt_m}\) for the modal value \(t_m\).&lt;/p&gt;

&lt;p&gt;So once we have \(b\) we can get \(\eta\) from the data by looking for
the year (or month) with the most deaths.&lt;/p&gt;

&lt;p&gt;Since this modal value \(t_m\) is the maximum of the Gompertz pdf, for
values \(t_0 \ge t_m\) the conditional pdf \(f_{t_0}\) has its maximum
at the beginning and becomes monotonically decreasing. This means
that after making it to that age, the single most likely moment of
death is the next one. But the expected remaining lifetime is
still positive and the hazard itself keeps climbing into the future.&lt;/p&gt;

&lt;p&gt;The \(b\) parameter we also get from the data as it determines the
year-on-year increase in the mortality rate: From the data above we
would estimate \(b=0.1\). Milevsky suggests using \(1/b = 9.5\) years
and calls this the &lt;em&gt;dispersion coefficient of human life&lt;/em&gt;.&lt;sup id=&quot;fnref:3&quot; role=&quot;doc-noteref&quot;&gt;&lt;a href=&quot;#fn:3&quot; class=&quot;footnote&quot; rel=&quot;footnote&quot;&gt;3&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;

&lt;p&gt;As the modal value of human life Milevsky suggests using \(t_m=87.25\)
for the general population in North America. Obviously \(t_m\) was lower
in Gompertz’s time; for a population of healthy females in a modern
society Milevsky suggests using up to \(t_m=90\).&lt;/p&gt;

&lt;h4 id=&quot;plugging-it-all-together&quot;&gt;Plugging it all together&lt;/h4&gt;

&lt;p&gt;For a member of the general population in a developed country we can
take \(b = 1/9.5\), \(t_m=87.25\) and therefore \(\eta = e^{- bt_m} =
e^{-87.25 / 9.5} \approx 1.026\cdot 10^{-4}\). If that person is
\(t_0\ge 0\) years old, the Gompertz pdf for their future looks like&lt;/p&gt;

\[b\eta e^{bt_0}\exp\bigl(-\eta e^{bt_0}(e^{bt}-1) + bt\bigr)
=
b e^{b(t_0 - t_m)} \exp\bigl(-e^{b(t_0 - t_m)}(e^{bt}-1) + bt\bigr)\]

&lt;p&gt;while the cdf is&lt;/p&gt;

\[1 - \exp\bigl(- e^{b(t_0-t_m)} (e^{bt} - 1)\bigr).\]

&lt;p&gt;Therefore, the survival function conditioned on having lived until
year \(t_0\) is&lt;/p&gt;

\[p_{t_0}(t) := \exp\bigl(- e^{b(t_0-t_m)} (e^{bt} - 1)\bigr).\]

&lt;p&gt;This is also the chance of still being alive at year \(t_0 + t\) given
being alive at year \(t_0\) and constitutes an answer to the question
of “How long will I spend in retirement?”, or more precisely “How
likely am I to be alive \(t\) years into my retirement?”. It’s also
Milevsky’s equation #2.&lt;/p&gt;

&lt;p&gt;In a future blogpost, we will use this to compute values of
annuities. For now, let’s wrap up with a quick discussion of how
realistic this model is.&lt;/p&gt;

&lt;h3 id=&quot;is-this-model-any-good&quot;&gt;Is this model any good?&lt;/h3&gt;

&lt;p&gt;The first thing to say is that sadly, human babies are more likely to
die than the Gompertz distribution would indicate. That’s partially a
sad fact of life and partially a consequence of the fact that severe
medical problems in unborn babies or during birth are less likely to
cause outright death at the point of delivery for the baby in
question, but may still cause death after a few days, months, or even
years.&lt;/p&gt;

&lt;p&gt;On a potentially more positive note, the Gompertz distribution might
&lt;em&gt;overestimate&lt;/em&gt; the chance of dying next year for very old people. As
&lt;a href=&quot;https://en.wikipedia.org/wiki/Gompertz%E2%80%93Makeham_law_of_mortality&quot;&gt;Wikipedia has
it&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;At more advanced ages, some studies have found that death rates
increase more slowly – a phenomenon known as the late-life mortality
deceleration – but more recent studies disagree.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Generally, there seems to be consensus that the Gompertz distribution
models mortality really well between the ages of 30 and 80.&lt;/p&gt;

&lt;p&gt;A question very dear to “transhumanists” is to what
extent the gains in longevity seen in the last centuries can be
expected to continue to happen in the future. Obviously a simple
two-parameter model won’t tell us a lot about that, and neither will
the three-parameter Gompertz-Makeham distribution. Still, I found it
interesting if a bit discouraging to read, again in
&lt;a href=&quot;https://en.wikipedia.org/wiki/Gompertz%E2%80%93Makeham_law_of_mortality&quot;&gt;Wikipedia&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;The decline in the human mortality rate before the 1950s was mostly
due to a decrease in the age-independent (Makeham) mortality
component, while the age-dependent (Gompertz) mortality component
was surprisingly stable. Since the 1950s, a new mortality
trend has started in the form of an unexpected decline in mortality
rates at advanced ages and “rectangularization” of the survival
curve.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;So apparently \(\eta\) and \(b\) have been stable over a long time
period. Whatever that says about human longevity, it also says the
Gompertz (or the Gompertz-Makeham) model is not so bad.&lt;/p&gt;

&lt;p&gt;That’s it for today. My apologies for not actually having any \(\pi\)s in all of
this after all :)&lt;/p&gt;
&lt;div class=&quot;footnotes&quot; role=&quot;doc-endnotes&quot;&gt;
  &lt;ol&gt;
    &lt;li id=&quot;fn:1&quot; role=&quot;doc-endnote&quot;&gt;
      &lt;p&gt;For Kolmogorov, I’d love to have another reference for his
  supposed &lt;em&gt;War and Peace&lt;/em&gt;-inspired nickname “ANK”. The book in question
  is the only reference I could find. &lt;a href=&quot;#fnref:1&quot; class=&quot;reversefootnote&quot; role=&quot;doc-backlink&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
    &lt;li id=&quot;fn:2&quot; role=&quot;doc-endnote&quot;&gt;
      &lt;p&gt;This works for probability measures that are absolutely
  continuous with respect to the Lebesgue measure, meaning such a
  Lebesgue density exists. All measures on the reals can be decomposed
  into such a measure, a discrete measure and a so-called singular
  continuous measure. Let’s just stay with Lebesgue densities here. &lt;a href=&quot;#fnref:2&quot; class=&quot;reversefootnote&quot; role=&quot;doc-backlink&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
    &lt;li id=&quot;fn:3&quot; role=&quot;doc-endnote&quot;&gt;
      &lt;p&gt;The “mortality rate” in the table above is the one-year
  conditional probability of dying, \(1 - \exp\bigl(-\int_t^{t+1}
  h(s)\,ds\bigr)\), not the hazard \(h(t)\) itself. The
  exponential comes from the survival function: \(S(t) =
  \exp\bigl(-\int_0^t h\bigr)\), so the conditional probability of
  surviving the year is \(S(t+1)/S(t) = \exp\bigl(-\int_t^{t+1}
  h\bigr)\), and the conditional probability of dying is one minus
  that. Both the hazard function \(h\) and this probability grow
  at \({\sim}10\%\)/year while \(h\) is small, since \(1 - e^{-x}
  = x + O(x^2)\), but the probability is bounded by 1 and saturates
  at extreme ages while \(h\) continues to grow exponentially. The
  Gompertz law is fundamentally a statement about \(h\); the table
  inherits it as an approximation. &lt;a href=&quot;#fnref:3&quot; class=&quot;reversefootnote&quot; role=&quot;doc-backlink&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
  &lt;/ol&gt;
&lt;/div&gt;
</description>
        <pubDate>Tue, 23 Mar 2021 00:00:00 +0000</pubDate>
        <link>https://heiner.ai/blog/2021/03/23/pis-deaths-and-statistics.html</link>
        <guid isPermaLink="true">https://heiner.ai/blog/2021/03/23/pis-deaths-and-statistics.html</guid>
        
        
        <category>blog</category>
        
      </item>
    
      <item>
        <title>Well-definedness in measure theory</title>
        <description>&lt;p&gt;This blog covers very niche topics. Today: How to easily show that the
Lebesgue measure and the Lebesgue integral is well-defined.&lt;/p&gt;

&lt;p&gt;I recently started reading the &lt;a href=&quot;https://banditalgs.com&quot;&gt;“Bandit Algorithms” book
by Tor Lattimore and Csaba
Szepesvari&lt;/a&gt;. &lt;a href=&quot;https://twitter.com/HeinrichKuttler/status/1343551842580639750&quot;&gt;I like it a
lot.&lt;/a&gt;
Chapter 2 there got me back to
one of my favorite topics in math: Measure Theory. While measure
theory is often held as being boring or dry, I disagree. It’s just
often presented in a suboptimal way. In particular, many authors get
so carried away by a progression of simple functions – positive
functions – real-valued functions that they forget that linearity is a
great thing (one symptom of this: Trying to find a “common partition”
for two simple functions).&lt;/p&gt;

&lt;p&gt;Here we present a simple lemma and its corollary that takes care of
most well-definedness questions in measure theory, in particular: Why
the extension of a pre-measure from a semiring to a ring is
well-defined (and therefore unique), and why the Lebesgue integral of
simple functions is well-defined.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lemma 1.&lt;/strong&gt; Let \(\H\) be a family of sets with the following partition
property: For each finite family \((A_1, \ldots, A_n)\) in \(\H\)
there is a finite disjoint family \((B_k\st k \in
K_0)\) in \(\H\) such that&lt;/p&gt;

\[\forall j \in\set{1,\ldots,n}\, \exists K_j \subseteq
K_0: A_j=\mathop{\dot{\bigcup}}_{k \in K_j} B_k.\]

&lt;p&gt;(In particular, either \(A_j \supseteq B_k\) or \(A_j\cap
B_k=\emptyset\) is true at all times, with
\(A_j\supseteq B_k \Leftrightarrow k \in K_j.\))&lt;/p&gt;

&lt;p&gt;Let \(\mu\from \H\to[0, \infty)\) be an additive set function (i.e.,
if \(A, B\in\H\) are disjoint with \(A\mathbin{\dot{\cup}} B\in\H\),
then \(\mu(A\mathbin{\dot{\cup}} B) = \mu(A) + \mu(B)\)). Let \(A_1, \ldots, A_n \in
\H\) and \(a_1, \ldots, a_n \in \F \in\set{\R, \mathbb{C}}\). Define&lt;/p&gt;

\[\qquad b_k:=\sum_{\substack{1\le j\le n\\ A_j\supseteq B_k}} a_j \where{k\in K_0}.\]

&lt;p&gt;Then \(\sum_{j=1}^n a_j \1_{A_j}=\sum_{k\in K_0} b_k\1_{B_k}\) and&lt;/p&gt;

\[\sum_{j=1}^n a_j \mu(A_j)=\sum_{k \in K_0} b_k
\mu(B_k)\]

&lt;p&gt;&lt;em&gt;Proof.&lt;/em&gt; The first statement follows directly from the definition of
\(b_k\). The second:&lt;/p&gt;

\[\begin{aligned} \sum_{j=1}^n a_j \mu(A_j)
&amp;amp;=\sum_{j=1}^n a_j \sum_{k \in K_j}
\mu(B_k) \\ &amp;amp;=\sum_{k \in K_0}
\underbrace{\sum_{j=1}^n \1_{K_j}(k) a_j}_{=b_k}
\mu(B_k)=\sum_{k \in K_0}
b_k \mu(B_k).  \qquad\text{//}\end{aligned}\]

&lt;p&gt;&lt;strong&gt;Corollary 2.&lt;/strong&gt; Let \(\H, \mu\) as in Lemma 1. Let
\(X:=\lin\set{\1_A\st A\in\H}\). Then \(J\from X\to\F\), defined via&lt;/p&gt;

\[X\ni f=\sum_{j=1}^n a_j \1_{A_j} \mapsto \sum_{j=1}^n a_j \mu(A_j),\]

&lt;p&gt;is well-defined and linear.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Proof.&lt;/em&gt; It suffices to treat the case \(f=0\). Let
\((B_k\st k \in K_0)\) be the disjoint representation and \((b_k\st b
\in K_0)\) as in Lemma 1. Then \(b_k=0\) for all \(k \in k_0,\) as
\(f=\sum_{j=1}^n a_j \1_{A_j}=\sum_{k \in
K_0} b_k \1_{B_k}\) and the \(B_k\) are pairwise disjoint. By Lemma 1,&lt;/p&gt;

\[\sum_{j=1}^n a_j \mu(A_j)
% =\sum_{j=1}^n a_j \mu(\mathop{\dot{\bigcup}}_{k \in k_j}B_k)
= \sum_{k\in K_0} b_k \mu(B_k)=0.\]

&lt;p&gt;This shows \(J\) is well-defined; it’s also clearly linear. //&lt;/p&gt;

&lt;p&gt;With this simple tool, we can look at our first application: The
Lebesgue-Stieltjes pre-measure.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lemma 3.&lt;/strong&gt; Let \(\H\) be the set of half-open intervals and let
\(\mathcal{R}\) be the ring of finite unions of
half-open intervals. Then each \(F \in \mathcal{R}\) is the disjoint
union of finitely many intervals.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Proof&lt;/em&gt; (Adapted from &lt;a href=&quot;http://www.math.tu-dresden.de/~voigt/mui/mui.pdf#page=7&quot;&gt;J. Voigt, “Einführung in die Integration”, Satz 1.1.1&lt;/a&gt;).
Let \(F=\bigcup_{j=1}^n
I_j\) with \(I_j=[a_j, b_j)\).
The set \(\set{a_j, b_j\st j=1,\ldots,n}\) can be written as
\(\set{x_k\st k=0,\ldots,m}\) with \(x_0 &amp;lt;x_2 &amp;lt; \cdots &amp;lt; x_m\). A set
of disjoint intervals with union \(F\) is&lt;/p&gt;

\[\{[x_{k-1}, x_k)\st
1\le k\le m \text{ and } \exists j\in\set{1,\ldots,n} :
[x_{k-1}, x_k) \subseteq[a_j,b_j)\}.  \qquad\text{//}\]

&lt;p&gt;&lt;strong&gt;Corollary 4.&lt;/strong&gt; Let \(G\from\R\to\R\) be
monotone. The mapping \(\mu\from\H\to[0,\infty)\),
defined via \(\mu([a,b)) := G(b)-G(a)\), can be uniquely extended to
an additive set function \(\mu\from\mathcal{R}\to[0, \infty)\).&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Proof.&lt;/em&gt; \(\mu\) is additive and \(\H\) has the partition property
from Lemma 1 by Lemma 3. Hence \(J\from X\to\F\) from Corollary 2 is
well-defined. Let \(F\in\mathcal{R}\). Then
\(\1_F\in X\) and thus \(\mu(F):=J(\1_F)\) is well-defined and \(\geq 0\).
This extension \(\mu\) is additive, since for \(\tilde{F}\in\mathcal{R}\),&lt;/p&gt;

\[\mu(F \mathbin{\dot{\cup}} \tilde{F}) =
J(\1_F+\1_{\tilde{F}}) = J(\1_F) + J(\1_{\tilde{F}}) =
\mu(F)+\mu(\tilde{F}).\]

&lt;p&gt;For the uniqueness: Let \(\tilde{\mu}\from\mathcal{R}\to[0,\infty)\)
be another additive extension and let \(F =
\mathop{\dot{\bigcup}}_{k=1}^m B_k \in\mathcal{R}\) with \(B_1, \ldots, B_m\in\H\).
Then&lt;/p&gt;

\[\tilde{\mu}(F)=\tilde{\mu}(\mathop{\dot{\bigcup}}
B_k)=\sum \tilde{\mu}(B_k)=\sum \mu(B_k)=\mu(F).  \qquad//\]

&lt;p&gt;If \(G\) left-continuous, \(\mu\) can be shown to be
\(\sigma\)-additive (and hence a pre-measure). One can then use
Carathéodory’s extension theorem to extend \(\mu\) to a measure on the
\(\sigma\)-algebra generated by \(\mathcal{R}\), which is the Borel
\(\sigma\)-algebra \(\mathcal{B}(\R)\).&lt;/p&gt;

&lt;p&gt;Later in the theory, Lemma 1 proves the well-definedness of the
Lebesgue integral for simple functions:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lemma 5.&lt;/strong&gt; Let \((\Omega, \mathcal{A}, \mu)\) be a measure space and
let \(f=\sum_{j=1}^n a_j \1_{A_j}\) be a simple function.
Then \(\int_\Omega f {~d}\mu:=\sum_{j=1}^n a_j \mu(A_j)\) is well-defined.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Proof.&lt;/em&gt; For \(K\subseteq K_0:=\{1, \ldots, n\}\), define&lt;/p&gt;

\[B_K:=\bigcap_{k\in K}
A_k \cap \bigcap_{k \in K_0 \setminus
K}(\Omega \setminus A_k)\]

&lt;p&gt;Then \((B_K\st \emptyset \neq K
\subseteq K_0)\) is a partition as in Corollary 2, and hence
\(\int f {~d}\mu=J(f)\) is well-defined. //&lt;/p&gt;

&lt;p&gt;This defines the Lebesgue integral for simple functions. Since simple
functions are dense in \(L_1(\mu)\), one is tempted to just use the
&lt;a href=&quot;https://en.wikipedia.org/wiki/Continuous_linear_extension&quot;&gt;BLT
theorem&lt;/a&gt;
now. That doesn’t quite work however, since the norm of \(L_1(\mu)\)
is defined via that integral in the first place. Instead, one can now
define the integral for positive functions via pointwise convergence
almost everywhere from below, then extend to real-valued (and
complex-valued) functions.&lt;/p&gt;
</description>
        <pubDate>Tue, 29 Dec 2020 00:00:00 +0000</pubDate>
        <link>https://heiner.ai/blog/2020/12/29/well-definedness-in-measure-theory.html</link>
        <guid isPermaLink="true">https://heiner.ai/blog/2020/12/29/well-definedness-in-measure-theory.html</guid>
        
        
        <category>blog</category>
        
      </item>
    
      <item>
        <title>More on linear regression: Capital asset pricing models</title>
        <description>&lt;p&gt;This is the long-awaited second part of February’s post on &lt;a href=&quot;/blog/2020/02/19/linear-regression.html&quot;&gt;Linear
Regression&lt;/a&gt;. This time,
without the needlessly abstract math, but with some classic portfolio
theory as an example of “applied linear regression”.&lt;/p&gt;

&lt;p&gt;We’ll be discussing two papers: &lt;a href=&quot;https://onlinelibrary.wiley.com/doi/full/10.1111/j.1540-6261.1968.tb00815.x&quot; target=&quot;_blank&quot;&gt;&lt;em&gt;The performance of mutual funds in
the period 1945-1964&lt;/em&gt; (1968) by Michael
Jensen&lt;/a&gt;
and &lt;a href=&quot;http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.139.5892&quot; target=&quot;_blank&quot;&gt;&lt;em&gt;Common Risk
Factors in the Returns On Stocks And Bonds&lt;/em&gt; (1993) by Eugene Fama
and Kenneth French&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Some disclaimers:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;I am by no means an expert on this topic. I learned about these
investing concepts on the &lt;a href=&quot;https://rationalreminder.ca&quot; target=&quot;_blank&quot;&gt;Rational Reminder
podcast&lt;/a&gt; by the
excellent Benjamin Felix and Cameron Passmore.&lt;/li&gt;
  &lt;li&gt;There’s many more results on this, both classic and
recent. The two papers discussed here added some delta at the time,
but previous results by others were essential too, and get no
mention here. I chose these two papers because they are relatively easy to
follow and their main message can be explained well in a blog post.&lt;/li&gt;
  &lt;li&gt;All of this is just for fun. Capital at risk.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;jensen-1968-standard-stuff&quot;&gt;Jensen (1968): Standard stuff.&lt;/h2&gt;

&lt;h4 id=&quot;on-models&quot;&gt;On models&lt;/h4&gt;

&lt;p&gt;The papers we discuss present &lt;em&gt;models&lt;/em&gt;. Models have assumptions as
well as domains in which they are valid and domains in which they are
not. We are not going to make precise statements about either of
these, but it’s useful to not confuse models with reality. ‘Whereof one
has no model thereof one must be silent’ (otherwise, &lt;em&gt;philosophus
mansisses&lt;/em&gt;). This is also known as &lt;a href=&quot;https://en.wikipedia.org/wiki/Streetlight_effect&quot; target=&quot;_blank&quot;&gt;searching under the
streetlights&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;em&gt;aim&lt;/em&gt; of our model will be to evaluate, or assess, the performance
of any given portfolio. Specifically, the model should evaluate
a portfolio manager’s ability to increase returns by successfully
predicting future prices for a &lt;em&gt;given level of riskiness&lt;/em&gt;. For
instance, if stock market returns are positive in expectation, a
leveraged portfolio could outperform an unleveraged portfolio without
any special forecasting ability on the manager’s part. Conversely, a
classical &lt;a href=&quot;https://www.investopedia.com/articles/financial-advisors/011916/why-6040-portfolio-no-longer-good-enough.asp&quot; target=&quot;_blank&quot;&gt;60/40 mix of stocks and
bonds&lt;/a&gt;
would likely do worse than a 100% equity portfolio in this case, but
may still be preferable due to its reduced risk. We won’t go into
detail how risk is measured, but we should mention that under certain
assumptions, it is precisely its riskiness that causes a given asset
to yield higher returns (&lt;em&gt;ceteris paribus&lt;/em&gt;, and on average): If
investors are risk-averse, they will need to be compensated for
taking on the additional risk of a specific asset compared to some
other asset, and higher expected future returns (expected future
prices relative to its current price) are the way that
compensation happens in a liquid market. Of course, the actual
expectation of any given investor may also just be wrong, but over
time one may expect the worst investors to drop out, improving the
accuracy of the average investor’s expectations.&lt;/p&gt;

&lt;h4 id=&quot;time-series-regressions&quot;&gt;Time series regressions&lt;/h4&gt;

&lt;p&gt;The specific models here do linear regression on time series. Suppose
we have one data point per time interval, e.g. per trading day:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;day&lt;/th&gt;
      &lt;th&gt; &lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;value&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;5 January 1970&lt;/td&gt;
      &lt;td&gt; &lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;388.8K&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;6 January 1970&lt;/td&gt;
      &lt;td&gt; &lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;475.2K&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt; &lt;/td&gt;
      &lt;td&gt;⋮&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt; &lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;We will use this data as an \(n\)-dimensional feature vector (aka explanatory
variable). Think of it as coming from the value of an index,
specifically from the capitalization-weighted value of the
whole stock market on that trading day. We will call this the &lt;em&gt;market
portfolio&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;The portfolio (or individual stock) we want to assess will also have a
value each trading day. This puts us in a situation in which we could
try to use linear regression to express our assessed portfolio as a
linear combination of the market value and a constant intercept
vector. However, little would be gained by just doing that – we’ll
have to at least normalize things a bit, otherwise this is what the
model will use its capacity (two numbers!) for. And while we are at
it, we remember that there used to be a time when the (almost, or by
definition) risk-free return offered by central banks was not
basically zero. To tease out the “risk factor”, we will use the market
return minus this risk-free rate as our feature vector. Our data thus
could look like this:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;day&lt;/th&gt;
      &lt;th&gt; &lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;market&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;risk-free&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;5 January 1970&lt;/td&gt;
      &lt;td&gt; &lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;1.21%&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0.029%&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;6 January 1970&lt;/td&gt;
      &lt;td&gt; &lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0.62%&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0.029%&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt; &lt;/td&gt;
      &lt;td&gt;⋮&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt; &lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt; &lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;For the risk-free rate, one could use the treasury bill rate. All these
numbers can in principle be retrieved from the historical
records (and in practice downloaded from &lt;a href=&quot;https://mba.tuck.dartmouth.edu/pages/faculty/ken.french/data_library.html&quot; target=&quot;_blank&quot;&gt;Kenneth French’s
homepage&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;Let’s call the market return \(R_M\) and the risk-free return
\(R_F\). A sensible regression without an intercept term could then
read as&lt;/p&gt;

\[R \approx R_F + \beta(R_M - R_F), \label{eq:1}\tag{1}\]

&lt;p&gt;where \(R\) is vector the observed returns of the portfolio or stock
we want to assess, and \(\beta\) is computed via the least-squares
condition of linear regression, i.e., \(\beta = \argmin\{\abs{R - R_F -
\beta(R_M - R_F)}_2\st \beta\in\R\}\), as in the &lt;a href=&quot;/blog/2020/02/19/linear-regression.html&quot; target=&quot;_blank&quot;&gt;last blog post&lt;/a&gt;. Notice that the \(R_F\)s
make sense here: It’s deviations from this risk-free return that we
want to model, and we want \(\beta\) to scale the non risk-free
portion of the market portfolio.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example.&lt;/strong&gt;  For a classic 60/40
portfolio with 60% whole market and 40% risk-free return (historically
not realistic for private investors, but easy to compute) we have&lt;/p&gt;

\[R - R_F= 0.6R_M + 0.4R_F - R_F = 0.6(R_M - R_F)\in\R^{n\times 1}\]

&lt;p&gt;and therefore, by the &lt;a href=&quot;/blog/2020/02/19/linear-regression.html&quot; target=&quot;_blank&quot;&gt;normal equation&lt;/a&gt;,&lt;/p&gt;

\[\beta = \bigl((R_M - R_F)^\top (R_M - R_F)\bigr)^{-1}
          (R_M - R_F)^\top (R - R_F) = 0.6.\]

&lt;p&gt;That seems sensible in this case.&lt;/p&gt;

&lt;h4 id=&quot;finding-alpha&quot;&gt;Finding Alpha&lt;/h4&gt;

&lt;p&gt;However, \eqref{eq:1} isn’t quite good enough: More precisely, it
reads&lt;/p&gt;

\[R = R_F + \beta(R_M - R_F) + e, \label{eq:2}\tag{2}\]

&lt;p&gt;with an error term \(e\in\R^n\). As Jensen (1968) argues,&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;[W]e must be very careful when applying the equation to managed portfolios. If the manager is a superior forecaster (perhaps because of
special knowledge not available to others) he will tend to systematically select
securities which realize [\(e_j &amp;gt; 0\)].&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This touches on a subject glossed over in the last blog post: Most
statements about linear regression models depend on certain
statistical assumptions, among them that
the error terms are elementwise iid, ideally with a mean of zero. There’s
autocorrelation tests like
&lt;a href=&quot;https://en.wikipedia.org/wiki/Durbin%E2%80%93Watson_statistic&quot; target=&quot;_blank&quot;&gt;Durbin-Watson&lt;/a&gt;
to test if this is true for a particular dataset. In this
particular modeling exercise, we can do better by
adding the constant \(\1=(1,\ldots,1)\in\R^n\) intercept vector to the
subspace we project on, which turns \eqref{eq:2} into&lt;/p&gt;

\[R - R_F = \alpha + \beta(R_M - R_F) + u, \label{eq:3}\tag{3}\]

&lt;p&gt;with an error term \(u\in\R^n\).&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Ever wondered where the
“&lt;a href=&quot;https://en.wikipedia.org/wiki/Alpha_(finance)&quot; target=&quot;_blank&quot;&gt;alpha&lt;/a&gt;” in the
clickbait website &lt;a href=&quot;https://seekingalpha.com/&quot; target=&quot;_blank&quot;&gt;Seeking Alpha&lt;/a&gt; comes
from?&lt;/em&gt; It is this \(\alpha\), the coefficient of the
\(\1\) intercept vector in \eqref{eq:3}. To quote
Jensen (1968) again:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Thus if the portfolio manager has an ability to forecast security prices, the
intercept, [\(\alpha\), in eq. \eqref{eq:3}] will be positive. Indeed,
it represents the average incremental rate of return on the portfolio
per unit time which is due solely to
the manager’s ability to forecast future security prices. It is
interesting to
note that a naive random selection buy and hold policy can be expected to
yield a zero intercept. In addition if the manager is not doing as
well as a
random selection buy and hold policy, [\(\alpha\)] will be
negative. At first glance it
might seem difficult to do worse than a random selection policy, but such
results may very well be due to the generation of too many expenses in unsuccessful forecasting attempts.&lt;/p&gt;

  &lt;p&gt;However, given that we observe a positive intercept in any sample of returns on a portfolio we have the difficulty of judging whether or not this
observation was due to mere random chance or to the superior forecasting
ability of the portfolio manager. […]&lt;/p&gt;

  &lt;p&gt;It should be emphasized that in estimating [\(\alpha\)], the measure
of performance,
we are explicitly allowing for the effects of risk on return as implied by the
asset pricing model. Moreover, it should also be noted that if the model is
valid, the particular nature of general economic conditions or the particular
market conditions (the behavior of \(\pi\)) over the sample or evaluation period
has no effect whatsoever on the measure of performance. Thus our measure
of performance can be legitimately compared across funds of different risk
levels and across different time periods irrespective of general economic and
market condition.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;About the error term \(u\), first notice that thanks to the intercept
term we can expect it to have a mean of zero. Further, Jensen (1968)
argues it “should be serially [i.e., elementwise] independent” as
otherwise “the manager could increase his return even more by
taking account of the information contained in the serial dependence
and would therefore eliminate it.”&lt;/p&gt;

&lt;h3 id=&quot;just-show-me-the-code&quot;&gt;Just show me the code!&lt;/h3&gt;

&lt;p&gt;After introducing this model, Jensen (1968) continues with “the data
and empirical results”. In ca. 2015 AI parlance, this part could be
called “Experiments”. Take a look at Table 1 in the paper to get a
list of quaint mutual fund names. Notice too that it’s not immediately
obvious how to get the market portfolio’s returns from historical
trading data, as companies enter and leave the stock market, and how
they leave will play a huge role. (Bankruptcy? Taken private at
$420?)&lt;/p&gt;

&lt;p&gt;For our purposes though, all of this has been taken care of and
&lt;a href=&quot;https://mba.tuck.dartmouth.edu/pages/faculty/ken.french/data_library.html&quot; target=&quot;_blank&quot;&gt;Kenneth French’s
homepage&lt;/a&gt;
has the data, including data for each trading day, in usable
formats.&lt;/p&gt;

&lt;p&gt;Let’s start by getting the data and sanity-checking our 60/40 example
above. All of the code in this post can also be &lt;a href=&quot;/src/ff3f.py&quot;&gt;downloaded
separately&lt;/a&gt; or
run in a &lt;a href=&quot;https://colab.research.google.com/drive/1iqpYDgpElizyAWW-6xXHMTpatw0Hqm1c?usp=sharing&quot; target=&quot;_blank&quot;&gt;Google Colab&lt;/a&gt;.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;os&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;re&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;urllib.request&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;zipfile&lt;/span&gt;

&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;FF3F&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Monthly data.
&lt;/span&gt;    &lt;span class=&quot;s&quot;&gt;&quot;https://mba.tuck.dartmouth.edu/pages/faculty/&quot;&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;ken.french/ftp/F-F_Research_Data_Factors_TXT.zip&quot;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;download&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;url&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;FF3F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;archive&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;os&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;path&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;basename&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;url&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;os&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;path&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;exists&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;archive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Retrieving&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;url&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;urllib&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;request&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;urlretrieve&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;url&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;archive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;archive&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;extract&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;archive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;match&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;re&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;compile&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;rb&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;\d&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;zipfile&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ZipFile&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;archive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rest&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;namelist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rest&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;open&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Filter for the actual data lines in the file.
&lt;/span&gt;            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loadtxt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;line&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;line&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;f&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;match&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;match&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;line&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;unpack&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;n&quot;&gt;date&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mktmrf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rf&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;extract&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;download&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;mkt&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mktmrf&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rf&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Linear regression using the normal equation.
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ones_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mktmrf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mktmrf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.6&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mkt&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.4&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rf&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;alpha=%f; beta=%f&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;As expected, this prints&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;alpha=0.000000; beta=0.600000
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;If we are seeking \(\alpha\), we’ll have to look elsewhere.&lt;/p&gt;

&lt;p&gt;Let’s try some real data. The biggest issue is getting hold of
the daily returns of real portfolios. Real researchers use data
sources like the &lt;a href=&quot;http://www.crsp.org/&quot; target=&quot;_blank&quot;&gt;Center for Research in Security Prices
(CRSP)&lt;/a&gt;, but their data isn’t available for
free. Instead, let’s the data for iShares S&amp;amp;P Small-Cap 600 Value ETF
(IJS) from &lt;a href=&quot;https://finance.yahoo.com/quote/IJS/history?period1=964742400&amp;amp;period2=1599350400&amp;amp;interval=1mo&amp;amp;filter=history&amp;amp;frequency=1mo&quot; target=&quot;_blank&quot;&gt;Yahoo
finance&lt;/a&gt;.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Continuing from above.
&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;time&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;IJS&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;https://gist.githubusercontent.com/heiner/b222d0985cbebfdfc77288404e6b2735/&quot;&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;raw/08c1cacecbcfcd9e30ce28ee6d3fe3d96c07115c/IJS.csv&quot;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;extract_csv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;archive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;open&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;archive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loadtxt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;delimiter&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;,&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;skiprows&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Header.
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;converters&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Hacky date handling.
&lt;/span&gt;                &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;time&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;strftime&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
                    &lt;span class=&quot;s&quot;&gt;&quot;%Y%m&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;time&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;strptime&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;decode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;ascii&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;%Y-%m-%d&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;p&quot;&gt;},&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;n&quot;&gt;ijs_data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;extract_csv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;download&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;IJS&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;ijs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ijs_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Adj Close (includes dividends).
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Turn into monthly percentage returns.
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ijs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ijs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ijs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ijs_date&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ijs_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;ijs_date&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;indices&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ijs_indices&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;intersect1d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;date&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ijs_date&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;return_indices&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Regression model for CAPM.
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ones_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ijs_date&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mktmrf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;indices&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ijs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ijs_indices&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;indices&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# R^2 and adjusted R^2.
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model_err&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ss_err&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_err&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_err&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;r2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ss_err&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ddof&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;adjr2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ss_err&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ddof&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;CAPM: alpha=%.2f%%; beta=%.2f. R^2=%.1f%%; R_adj^2=%.1f%%. Annualized alpha: %.2f%%&quot;&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;r2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adjr2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This prints:&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;CAPM: alpha=0.13%; beta=1.14. R^2=77.8%; R_adj^2=77.7%. Annualized alpha: 1.58%
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Since \(\alpha\) is the weight for the constant intercept vector \(\1
= (1,\ldots,1)\), we can think of it as having percentage points as
its unit. Note that fees are not included in this calculation.
However, as for many ETFs fees for IJS are low, currently at 0.25%
per year. (Managed mutual funds will typically have an
annual fee of at least 1%, historically often more than that.)&lt;/p&gt;

&lt;p&gt;It seems bit strange that this ETF tracking the  S&amp;amp;P Small-Cap 600
Value index has significant \(\alpha\): Presumably, the index just
includes firms based on simple rules, not genius insights by some
above-average fund manager. Looking at the \(R^2\) value, we “explain”
only 77% of the variance of the returns of IJS (the usual caveats
to the wording “explain” apply).&lt;/p&gt;

&lt;p&gt;Clearly more research was needed. Or just a larger subspace for the
linear regression to project onto?&lt;/p&gt;

&lt;h2 id=&quot;fama--french-1993-more-factors&quot;&gt;Fama &amp;amp; French (1993): More factors.&lt;/h2&gt;

&lt;p&gt;By the 1980s, research
into financial economics had noticed that certain segments of the market
outperformed other segments, and thus the market as a whole, on
average. There are several possible explanations for this effect with
different implications for the future. For example: Are these segments
of the market just inherently riskier such that rational traders
demand higher expected returns via sufficiently low prices for these
stocks? Or were traders
just irrationally disinterested in some ‘unsexy’ firms and have
perhaps caught on by now (or not, hence TSLA)? The latter is the
behavioural explanation, while the former tends to be put
forth by proponents of the &lt;a href=&quot;https://en.wikipedia.org/wiki/Efficient-market_hypothesis&quot; target=&quot;_blank&quot;&gt;Efficient-market hypothesis
(EMH)&lt;/a&gt;,
which includes
&lt;a href=&quot;https://en.wikipedia.org/wiki/The_Superinvestors_of_Graham-and-Doddsville&quot; target=&quot;_blank&quot;&gt;Jensen&lt;/a&gt;
as well as Fama and French.
We won’t be getting into this now. Let’s instead take
a look at which ‘easily’ identifiable segments of the market have
historically outperformed.&lt;/p&gt;

&lt;p&gt;Citing previous literature, Fama &amp;amp; French (1993) mention &lt;em&gt;size&lt;/em&gt;
(market capitalization, i.e., price per stock times number of shares),
&lt;em&gt;earnings per price&lt;/em&gt; and &lt;em&gt;book-to-market&lt;/em&gt; (book value divided by
market value) as variables that appear to have “explanatory power”,
which I take to mean that some model that includes these variables has
nonzero regression coefficients and a relatively large \(R^2\) or other
appropriate statistics.&lt;/p&gt;

&lt;p&gt;The specific way in which Fama &amp;amp; French (1993) introduce these variables into
the model is through the construction of portfolios that mimic these
variables. This approach contributed to their being awarded the
Nobel (Memorial) Prize in Economic Sciences in 2013. The specific
construction goes as follows:&lt;/p&gt;

&lt;p&gt;Take all stocks in the overall market and order them by their size
(i.e., market capitalization). Then take the top and bottom halves and
call them “&lt;em&gt;big&lt;/em&gt;” (&lt;em&gt;B&lt;/em&gt;) and “&lt;em&gt;small&lt;/em&gt;” (&lt;em&gt;S&lt;/em&gt;), respectively.&lt;/p&gt;

&lt;p&gt;Next, again take all stocks in the overall market and order them by
book-to-market equity. Then take the bottom 30% (“&lt;em&gt;low&lt;/em&gt;”, &lt;em&gt;L&lt;/em&gt;), the middle 40%
(“&lt;em&gt;medium&lt;/em&gt;”, &lt;em&gt;M&lt;/em&gt;), and the top 30% (“&lt;em&gt;high&lt;/em&gt;”, &lt;em&gt;H&lt;/em&gt;). In both cases, some care
needs to be taken: E.g., how to handle firms dropping in and out of the
market, how to define book equity properly in the presence of deferred
taxes, and other effects.&lt;/p&gt;

&lt;p&gt;Then, construct the six portfolios containing stocks in the
intersections of the two size and the three book-to-market equity
groups, e.g.&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: right&quot;&gt; &lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;low&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;medium&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;high&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;&lt;strong&gt;small&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;em&gt;S/L&lt;/em&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;em&gt;S/M&lt;/em&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;em&gt;S/H&lt;/em&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;&lt;strong&gt;big&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;em&gt;B/L&lt;/em&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;em&gt;B/M&lt;/em&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;em&gt;B/H&lt;/em&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Out of these six building blocks, Fama &amp;amp; French build a &lt;em&gt;size&lt;/em&gt; and a
&lt;em&gt;book-to-market equity&lt;/em&gt; portfolio:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;The &lt;em&gt;size&lt;/em&gt; portfolio is “small minus
big” (&lt;em&gt;SMB&lt;/em&gt;) consisting of the monthly difference of the three
small-stock portfolios &lt;em&gt;S/L&lt;/em&gt;, &lt;em&gt;S/M&lt;/em&gt;, and &lt;em&gt;S/H&lt;/em&gt; to the three big-stock
portfolios &lt;em&gt;B/L&lt;/em&gt;, &lt;em&gt;B/M&lt;/em&gt;, and &lt;em&gt;B/H&lt;/em&gt;.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;The &lt;em&gt;book-to-market equity&lt;/em&gt; portfolio is “high minus low” (&lt;em&gt;HML&lt;/em&gt;),
the monthly difference of the two high book-to-market
portfolios &lt;em&gt;S/H&lt;/em&gt; and &lt;em&gt;B/H&lt;/em&gt; to the two low book-to-market
portfolios &lt;em&gt;S/L&lt;/em&gt; and &lt;em&gt;B/L&lt;/em&gt;. This is also known as the &lt;em&gt;value&lt;/em&gt;
factor.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Additionally, the authors also use the &lt;em&gt;market portfolio&lt;/em&gt; as “market
return minus risk-free return (one-month treasury bill rate)” in the
same way as Jensen (1968).&lt;/p&gt;

&lt;h4 id=&quot;an-aside&quot;&gt;An aside&lt;/h4&gt;

&lt;p&gt;I’m not sure why &lt;em&gt;SMB&lt;/em&gt; and &lt;em&gt;HML&lt;/em&gt; need the to have their
two terms be equally weighted among the splits of the other
ordering. The authors mention&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;[For &lt;em&gt;HML&lt;/em&gt;] the difference between the two returns should be largely free of
the size factor in returns, focusing instead on the different return
behaviors of high- and low-[book-to-market] firms. As testimony to the
success of this simple procedure, the correlation between the
1963–1991 monthly mimicking returns for the size and
book-to-market factors is only \(- 0.08\).&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Taking “correlation” to mean the Pearson correlation coefficient, we
can test this using the data from French’s homepage:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;date&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mktmrf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;smb&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hml&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rf&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;extract&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;download&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;corrcoef&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;smb&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hml&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This prints&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;[[1.         0.12889074]
 [0.12889074 1.        ]]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;which implies a coefficient of \(0.13\). In 1993, Fama and French had
less data available: The paper uses the 342 months from July 1963 to
December 1991. Let’s check with this range:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;orig_indices&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;196307&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;date&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;date&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;199112&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;smb&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;orig_indices&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;342&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;corrcoef&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;smb&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;orig_indices&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hml&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;orig_indices&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This yields&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;[[ 1.         -0.09669641]
 [-0.09669641  1.        ]]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;a coefficient of roughly \(-0.10\), not the \(-0.08\) the authors
mention, but relatively close. I guess the data has been cleaned a bit
since 1993?&lt;/p&gt;

&lt;p&gt;As a further aside, accumulating this data and analyzing it was a true
feat in 1993. These days, we can do the same using the internet and
a few lines of Python (or, spoiler alert, using just a
&lt;a href=&quot;https://www.portfoliovisualizer.com/&quot; target=&quot;_blank&quot;&gt;website&lt;/a&gt;).&lt;/p&gt;

&lt;h4 id=&quot;back-to-modelling&quot;&gt;Back to modelling&lt;/h4&gt;

&lt;p&gt;So what are we to do with &lt;em&gt;SMB&lt;/em&gt; and &lt;em&gt;HML&lt;/em&gt;? You guessed it – just add
them to the regression model. Of course, this makes the subspace we
project on larger, which will always decrease the “fraction of
variance unexplained”, without necessarily explaining much. However,
in the case of IJS it appears to explain a bit:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Continuing from above.
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ones_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ijs_date&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mktmrf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;indices&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;smb&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;indices&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hml&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;indices&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ijs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ijs_indices&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;indices&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_mkt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_smb&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_hml&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model_err&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ss_err&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_err&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_err&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;r2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ss_err&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ddof&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;adjr2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ss_err&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ddof&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;FF3F: alpha=%.2f%%; beta_mkt=%.2f; beta_smb=%.2f; beta_hml=%.2f.&quot;&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot; R^2=%.1f%%; R_adj^2=%.1f%%. Annualized alpha: %.2f%%&quot;&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;beta_mkt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;beta_smb&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;beta_hml&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;r2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adjr2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This prints:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;FF3F: alpha=0.04%; beta_mkt=0.97; beta_smb=0.79; beta_hml=0.51. R^2=95.8%; R_adj^2=95.8%. Annualized alpha: 0.43%
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;In other words, we dropped from an (annualized) \(\alpha_{\rm CAPM} = 1.58\%\) to
only \(\alpha_{\rm FF3F} = 0.43\%\). The explained fraction of
variance has increased to above 95%.&lt;/p&gt;

&lt;p&gt;Remembering that Jensen (1968) talked about assessing fund managers
with this model, we could try the same with actual managed
funds. While I couldn’t produce any impressive results there, French
and Fama did go into the question of &lt;a href=&quot;http://mba.tuck.dartmouth.edu/bespeneckbo/default/AFA611-Eckbo%20web%20site/AFA611-S8C-FamaFrench-LuckvSkill-JF10.pdf&quot; target=&quot;_blank&quot;&gt;&lt;em&gt;Luck versus Skill in the
Cross-Section of Mutual Fund
Returns&lt;/em&gt;&lt;/a&gt;
in a 2010 paper. The results, on average, don’t look good for fund
managers’ skill. The story for individual fund managers may be better,
but don’t hold your breath.&lt;/p&gt;

&lt;h3 id=&quot;was-this-worth-it&quot;&gt;Was this worth it?&lt;/h3&gt;

&lt;p&gt;We discussed academic outputs of Jensen, French and Fama. The latter
two even got a Nobel for
their work on factor models. But nowadays, we can do (parts) of their
computations in a few lines of Python.&lt;/p&gt;

&lt;p&gt;It’s actually easier than that still. The website
portfoliovisualizer.com allows us to do &lt;a href=&quot;https://www.portfoliovisualizer.com/factor-analysis?s=y&amp;amp;regressionType=1&amp;amp;symbols=IJS&amp;amp;sharedTimePeriod=true&amp;amp;factorDataSet=0&amp;amp;marketArea=0&amp;amp;factorModel=1&amp;amp;useHMLDevFactor=false&amp;amp;includeQualityFactor=false&amp;amp;includeLowBetaFactor=false&amp;amp;fixedIncomeFactorModel=0&amp;amp;__checkbox_ffmkt=true&amp;amp;__checkbox_ffsmb=true&amp;amp;__checkbox_ffsmb5=true&amp;amp;__checkbox_ffhml=true&amp;amp;__checkbox_ffmom=true&amp;amp;__checkbox_ffrmw=true&amp;amp;__checkbox_ffcma=true&amp;amp;__checkbox_ffstrev=true&amp;amp;__checkbox_ffltrev=true&amp;amp;__checkbox_aqrmkt=true&amp;amp;__checkbox_aqrsmb=true&amp;amp;__checkbox_aqrhml=true&amp;amp;__checkbox_aqrhmldev=true&amp;amp;__checkbox_aqrmom=true&amp;amp;__checkbox_aqrqmj=true&amp;amp;__checkbox_aqrbab=true&amp;amp;__checkbox_aamkt=true&amp;amp;__checkbox_aasmb=true&amp;amp;__checkbox_aahml=true&amp;amp;__checkbox_aamom=true&amp;amp;__checkbox_aaqmj=true&amp;amp;__checkbox_qmkt=true&amp;amp;__checkbox_qme=true&amp;amp;__checkbox_qia=true&amp;amp;__checkbox_qroe=true&amp;amp;__checkbox_qeg=true&amp;amp;__checkbox_trm=true&amp;amp;__checkbox_cdt=true&amp;amp;timePeriod=2&amp;amp;rollPeriod=12&amp;amp;marketAssetType=1&amp;amp;robustRegression=false&quot; target=&quot;_blank&quot;&gt;all
of&lt;/a&gt;
&lt;a href=&quot;https://www.portfoliovisualizer.com/factor-analysis?s=y&amp;amp;regressionType=1&amp;amp;symbols=IJS&amp;amp;sharedTimePeriod=true&amp;amp;factorDataSet=0&amp;amp;marketArea=0&amp;amp;factorModel=3&amp;amp;useHMLDevFactor=false&amp;amp;includeQualityFactor=false&amp;amp;includeLowBetaFactor=false&amp;amp;fixedIncomeFactorModel=0&amp;amp;__checkbox_ffmkt=true&amp;amp;__checkbox_ffsmb=true&amp;amp;__checkbox_ffsmb5=true&amp;amp;__checkbox_ffhml=true&amp;amp;__checkbox_ffmom=true&amp;amp;__checkbox_ffrmw=true&amp;amp;__checkbox_ffcma=true&amp;amp;__checkbox_ffstrev=true&amp;amp;__checkbox_ffltrev=true&amp;amp;__checkbox_aqrmkt=true&amp;amp;__checkbox_aqrsmb=true&amp;amp;__checkbox_aqrhml=true&amp;amp;__checkbox_aqrhmldev=true&amp;amp;__checkbox_aqrmom=true&amp;amp;__checkbox_aqrqmj=true&amp;amp;__checkbox_aqrbab=true&amp;amp;__checkbox_aamkt=true&amp;amp;__checkbox_aasmb=true&amp;amp;__checkbox_aahml=true&amp;amp;__checkbox_aamom=true&amp;amp;__checkbox_aaqmj=true&amp;amp;__checkbox_qmkt=true&amp;amp;__checkbox_qme=true&amp;amp;__checkbox_qia=true&amp;amp;__checkbox_qroe=true&amp;amp;__checkbox_qeg=true&amp;amp;__checkbox_trm=true&amp;amp;__checkbox_cdt=true&amp;amp;timePeriod=2&amp;amp;rollPeriod=12&amp;amp;marketAssetType=1&amp;amp;robustRegression=false&quot; target=&quot;_blank&quot;&gt;these
computations&lt;/a&gt;
and more with a few clicks. In that sense, this blog post was perhaps
not worth it.&lt;/p&gt;

&lt;p&gt;Another question is how useful these models are. This touches on &lt;em&gt;why&lt;/em&gt;
&lt;em&gt;SMB&lt;/em&gt; and &lt;em&gt;HML&lt;/em&gt; ‘explain’ returns of portfolios (e.g., the risk
explanation vs the behavioural explanation mentioned above, or perhaps
both or neither). In
2014, Fama and French presented another updated model with five
factors, adding &lt;em&gt;profitability&lt;/em&gt; and &lt;em&gt;investment&lt;/em&gt;; judged by \(R^2\),
this five-factor model ‘explains’ even more of the variance of example
portfolios. Other research
suggesting alternative factors abounds.&lt;/p&gt;

&lt;p&gt;How well do these models
really ‘explain’ the phenomenal historical returns of star investors
like Warren Buffett? Given that Buffett is a proponent of the &lt;a href=&quot;https://en.wikipedia.org/wiki/Benjamin_Graham&quot; target=&quot;_blank&quot;&gt;Benjamin
Graham&lt;/a&gt; school of
&lt;em&gt;value investing&lt;/em&gt;, including a value factor like &lt;em&gt;HML&lt;/em&gt; could perhaps
be the key to explain his success?
For the Fama &amp;amp; French five-factor model, we can
check
&lt;a href=&quot;https://www.portfoliovisualizer.com/factor-analysis?s=y&amp;amp;regressionType=1&amp;amp;symbols=BRK.A&amp;amp;sharedTimePeriod=true&amp;amp;factorDataSet=0&amp;amp;marketArea=0&amp;amp;factorModel=5&amp;amp;useHMLDevFactor=false&amp;amp;includeQualityFactor=false&amp;amp;includeLowBetaFactor=false&amp;amp;fixedIncomeFactorModel=0&amp;amp;__checkbox_ffmkt=true&amp;amp;__checkbox_ffsmb=true&amp;amp;__checkbox_ffsmb5=true&amp;amp;__checkbox_ffhml=true&amp;amp;__checkbox_ffmom=true&amp;amp;__checkbox_ffrmw=true&amp;amp;__checkbox_ffcma=true&amp;amp;__checkbox_ffstrev=true&amp;amp;__checkbox_ffltrev=true&amp;amp;__checkbox_aqrmkt=true&amp;amp;__checkbox_aqrsmb=true&amp;amp;__checkbox_aqrhml=true&amp;amp;__checkbox_aqrhmldev=true&amp;amp;__checkbox_aqrmom=true&amp;amp;__checkbox_aqrqmj=true&amp;amp;__checkbox_aqrbab=true&amp;amp;__checkbox_aamkt=true&amp;amp;__checkbox_aasmb=true&amp;amp;__checkbox_aahml=true&amp;amp;__checkbox_aamom=true&amp;amp;__checkbox_aaqmj=true&amp;amp;__checkbox_qmkt=true&amp;amp;__checkbox_qme=true&amp;amp;__checkbox_qia=true&amp;amp;__checkbox_qroe=true&amp;amp;__checkbox_qeg=true&amp;amp;__checkbox_trm=true&amp;amp;__checkbox_cdt=true&amp;amp;timePeriod=2&amp;amp;rollPeriod=12&amp;amp;marketAssetType=1&amp;amp;robustRegression=false&quot; target=&quot;_blank&quot;&gt;portfoliovisualizer.com&lt;/a&gt;:
With \(R^2 \approx 33\%\), and an annualized \(\alpha\) of 4.87%, the results
don’t look too good for the math nerds but very good for the ‘Oracle
of Omaha’.&lt;/p&gt;

&lt;p&gt;This is obviously not a new observation. There is even a paper by a
number of people from investment firm AQR about &lt;a href=&quot;https://www.tandfonline.com/doi/full/10.2469/faj.v74.n4.3&quot; target=&quot;_blank&quot;&gt;&lt;em&gt;Buffett’s
Alpha&lt;/em&gt;&lt;/a&gt;
that aims to explain Buffett’s successes with leveraging as well as
yet another set of new factors in a linear regression model:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;[Buffett’s] alpha became insignificant, however, when we controlled
  for exposure to the factors “betting against beta” and “quality
  minus junk.”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Nice as this may sound, it would appear more convincing to this author
if the financial analysis community could converge on a small common
set of factors instead of seemingly creating them &lt;em&gt;ad hoc&lt;/em&gt;. Otherwise,
von Neumann’s line comes to mind: “With four parameters I can fit an
elephant, and with five I can make him wiggle his trunk.”&lt;/p&gt;

&lt;h3 id=&quot;and-now-what&quot;&gt;And now what?&lt;/h3&gt;

&lt;p&gt;We discussed two financial economics papers and the linear regression
models they propose, merely to give us a sense of what’s done in this
field. One may get a sense that this research should be useful for
more than just amusement, perhaps it could even inform our investment
choices? Many good &lt;a href=&quot;https://www.youtube.com/watch?v=ViTnIebSzj4&quot; target=&quot;_blank&quot;&gt;financial
advisors&lt;/a&gt; will make use
of data analyses
like this and suggest &lt;em&gt;factor-tilted&lt;/em&gt; portfolios. However, value
investing, both with factors as well as the Buffett/Munger variety,
has trailed the overall market in the last 10–15
years. Statistically, this is to be expected to happen every now and
then, so we cannot read too much into that. But it’s &lt;em&gt;possible&lt;/em&gt; the
market has just caught on, past performance is not indicative of
future results and value investing should be cancelled in 2020.
That would at least match the &lt;em&gt;zeitgeist&lt;/em&gt;. However, it’s also
entirely possible it’s exactly times like the present that make value
investing hard but ultimately worthwhile and we should be greedy when
others are fearful.&lt;/p&gt;

&lt;p&gt;Time will tell.&lt;/p&gt;

&lt;h4 id=&quot;references&quot;&gt;References&lt;/h4&gt;
&lt;ul class=&quot;simplelist&quot;&gt;
  &lt;li&gt;Frazzini, Andrea &amp;amp; Kabiller, David &amp;amp; Pedersen, Lasse Heje.
&lt;a href=&quot;https://www.tandfonline.com/doi/full/10.2469/faj.v74.n4.3&quot; target=&quot;_blank&quot;&gt;&lt;em&gt;Buffett’s Alpha&lt;/em&gt;&lt;/a&gt;.
Financ. Anal. J. 74 (4), 35–55
&lt;span class=&quot;smallcaps&quot;&gt;&lt;a href=&quot;https://doi.org/10.2469/faj.v74.n4.3&quot; target=&quot;_blank&quot;&gt;DOI:10.2469/faj.v74.n4.3&lt;/a&gt;&lt;/span&gt;.&lt;/li&gt;
  &lt;li&gt;Fama, Eugene F. &amp;amp; French, Kenneth R.
&lt;a href=&quot;http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.139.5892&quot; target=&quot;_blank&quot;&gt;&lt;em&gt;Common risk factors in the returns on stocks and bonds&lt;/em&gt;&lt;/a&gt;.
J. Financ. Econ. 33, (1), 3–56 (1993).
&lt;span class=&quot;smallcaps&quot;&gt;&lt;a href=&quot;https://doi.org/10.1016/0304-405X(93)90023-5&quot; target=&quot;_blank&quot;&gt;DOI:10.1016/0304-405X(93)90023-5&lt;/a&gt;&lt;/span&gt;.&lt;/li&gt;
  &lt;li&gt;———.
&lt;a href=&quot;http://mba.tuck.dartmouth.edu/bespeneckbo/default/AFA611-Eckbo%20web%20site/AFA611-S8C-FamaFrench-LuckvSkill-JF10.pdf&quot; target=&quot;_blank&quot;&gt;&lt;em&gt;Luck versus skill in the cross‐section of mutual fund
returns&lt;/em&gt;&lt;/a&gt;.
J. Financ. 65 (5), 1915–1947 (2010).
&lt;span class=&quot;smallcaps&quot;&gt;&lt;a href=&quot;https://doi.org/10.1111/j.1540-6261.2010.01598.x&quot; target=&quot;_blank&quot;&gt;DOI:10.1111/j.1540-6261.2010.01598.x&lt;/a&gt;&lt;/span&gt;.&lt;/li&gt;
  &lt;li&gt;———.
&lt;a href=&quot;https://tevgeniou.github.io/EquityRiskFactors/bibliography/FiveFactor.pdf&quot; target=&quot;_blank&quot;&gt;&lt;em&gt;A five-factor asset pricing model&lt;/em&gt;&lt;/a&gt;.
J. Financ. Econ. 116 (1), 1–22 (2015).
&lt;span class=&quot;smallcaps&quot;&gt;&lt;a href=&quot;https://doi.org/10.1016/j.jfineco.2014.10.010&quot; target=&quot;_blank&quot;&gt;DOI:10.1016/j.jfineco.2014.10.010&lt;/a&gt;&lt;/span&gt;.&lt;/li&gt;
  &lt;li&gt;Jensen, Michael C.
&lt;a href=&quot;https://onlinelibrary.wiley.com/doi/full/10.1111/j.1540-6261.1968.tb00815.x&quot; target=&quot;_blank&quot;&gt;&lt;em&gt;The performance of mutual funds in the period 1945–1964&lt;/em&gt;&lt;/a&gt;.
J. Financ. 23 (2), 389–416 (1968).
&lt;span class=&quot;smallcaps&quot;&gt;&lt;a href=&quot;https://doi.org/10.1111/j.1540-6261.1968.tb00815.x&quot; target=&quot;_blank&quot;&gt;DOI:10.1111/j.1540-6261.1968.tb00815.x&lt;/a&gt;&lt;/span&gt;.&lt;/li&gt;
&lt;/ul&gt;
</description>
        <pubDate>Tue, 08 Sep 2020 00:00:00 +0000</pubDate>
        <link>https://heiner.ai/blog/2020/09/08/more-linear-regression-capm.html</link>
        <guid isPermaLink="true">https://heiner.ai/blog/2020/09/08/more-linear-regression-capm.html</guid>
        
        
        <category>blog</category>
        
      </item>
    
      <item>
        <title>On linear regression</title>
        <description>&lt;p&gt;&lt;small&gt;[Edit 14 May 2020: Thanks to Marcus Waurick for pointing out \(A\)
needs to have close range for Lemmas 1 and 2 to be true in
general. Unfortunately, there seems no easy way of doing linear
regression in general Hilbert spaces (no equivalent of \(\1\),
although the idea of using weighted \(L_2\) spaces and writing a
blog post on &lt;em&gt;Linear Regression in Hilbert spaces with Morgenstern
norm&lt;/em&gt; has a certain ring to it.]&lt;/small&gt;&lt;/p&gt;

&lt;p&gt;Apropos of nothing, this is a post about linear regression. There’s a
whole world of information on that out there, but little with the
right point of view: The Hilbert space perspective. That might not
be universally loved, so you might feel more comfortable reading
\(\H_1 = \R^m\), \(\H_2 = \R^n\) and “matrix” in place of “linear
operator” below.&lt;/p&gt;

&lt;p&gt;We’ll do the short theory up front, then look at an example, then
say something about “fraction of variance explained”. A later blog
post will discuss the CAPM, French-Fama models and efficient markets as examples.&lt;/p&gt;

&lt;h2 id=&quot;two-lemmas&quot;&gt;Two lemmas.&lt;/h2&gt;

&lt;p&gt;Let \(\H_1\), \(\H_2\) be Hilbert spaces and \(A\in L(\H_1,\H_2)\) be
a linear operator with closed range (i.e., \(\overline{\im A} = \im A\)).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lemma 1.&lt;/strong&gt;  \(\H_2 = \im A\oplus\ker A^*\) in the sense of direct sums
of Hilbert spaces.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Proof&lt;/em&gt; Let \(x\in\im A\), \(y\in\ker A^*\). There is a \(x_1\in\H_1\)
with \(x = Ax_1\) and&lt;/p&gt;

\[\langle x,y\rangle = \langle Ax_1, y\rangle = \langle x_1, A^*
y\rangle = 0.\]

&lt;p&gt;Thus \(\im A\perp\ker A^*\).&lt;/p&gt;

&lt;p&gt;Reversely let \(y\in(\im A)^\perp\). Then \(0 = \langle Ax_1,
y\rangle = \langle x_1, A^* y\rangle\) for all \(x_1\in\H_1\), and
thus \(y\in\ker A^*\).   //&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lemma 2.&lt;/strong&gt;  Let \(P\from\H_2\to\im A\) be the orthogonal
projection.&lt;/p&gt;

&lt;p&gt;(a) Let \(y\in\H_2\). Then there is a \(b\in\H_1\) such that \(A^*Ab =
A^*y\) and \(Py = Ab\). This is called the &lt;em&gt;normal equation&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;(b) If \(\ker A = \{0\}\), i.e., \(A\) injective, then \(P =
A(A^*A)^{-1}A^*\).&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Proof.&lt;/em&gt; (a) There is \(b\in\H_2\) with \(Py = Ab\). Also \(y - Py\in(\im
A)^\perp\), and thus by Lemma 1&lt;/p&gt;

\[0 = A^*(y -Py) = A^*(y - Ab) = A^*y - A^*Ab.\]

&lt;p&gt;(b) Lemma 1 implies \(\H_1 = \im A^*\oplus\ker A = \im A^*\),
i.e. \(A^*\) is surjective. Since \(\im A = (\ker A^*)^\perp\) and
evidently \(A^*\from(\ker A^*)^\perp\to\H_1\) is injective, that
mapping is bijective. Additionally
\(A\from\H_1\to\im A\) is bijective, and thus \(A^*A\from\H_1\to\H_1\)
is bijective and invertible. Using (a) it follows that \(Py = Ab =
A(A^*A)^{-1}A^*y\).   //&lt;/p&gt;

&lt;h2 id=&quot;linear-regression-as-projection-to-subspaces&quot;&gt;Linear regression as projection to subspaces.&lt;/h2&gt;

&lt;h3 id=&quot;example-warships&quot;&gt;Example: Warships&lt;/h3&gt;

&lt;p&gt;To take a &lt;a href=&quot;https://de.wikipedia.org/wiki/Bestimmtheitsma%C3%9F#Rechenbeispiel&quot;&gt;favorite example from German
Wikipedia&lt;/a&gt;,
let’s discuss warships from the Second World War. Let’s say we’ve got
\(x_1\in\R^n\), a list of lengths of \(n\) warships, \(x_2\in\R^n\) a list
of their beams (widths) and \(y\in\R^n\) a list of their
drafts (distance from bottom to waterline), all in meters. We call
\(x_1\) and \(x_2\) &lt;em&gt;feature vectors&lt;/em&gt; (also known as &lt;em&gt;explanatory&lt;/em&gt; or
&lt;em&gt;independent&lt;/em&gt; variables) and can safely assume they are
linearly independent, such that the matrix&lt;/p&gt;

\[A = \begin{pmatrix}
  | &amp;amp; | \\
  x_1 &amp;amp; x_2 \\
  | &amp;amp; |
\end{pmatrix}\in\R^{n\times 2}\]

&lt;p&gt;defines an injective operator. Its image is the linear span of \(x_1\)
and \(x_2\), i.e., \(\im A = \{\alpha x_1 + \beta x_2 \st \alpha,
\beta\in\R\}\subseteq\R^n\). We wouldn’t expect \(y\) to be an element
of \(\im A\), but the hope of a linear regression model trying to
predict a warship’s draft from its length and beam is that \(y\)
is not too far from \(\im A\) as a subspace of \(\R^n\)
either. Specifically, the \(\abs{\dotid}_2\)-distance is&lt;/p&gt;

\[\dist(\{y\}, \im A) = \min_{y&apos;\in\im A}\abs{y - y&apos;}_2 = \abs{y - P y}_2\]

&lt;p&gt;where \(P\from\R^n\to\im A\) is the orthogonal projection. We can call
\(Py\) the model’s prediction, and Lemma 2 above tells us how to
compute \(P\) from \(A\), namely \(P = A(A^\top A)^{-1}A^\top\). Moreover, the
normal equation tells us which linear combination&lt;sup id=&quot;fnref:1&quot; role=&quot;doc-noteref&quot;&gt;&lt;a href=&quot;#fn:1&quot; class=&quot;footnote&quot; rel=&quot;footnote&quot;&gt;1&lt;/a&gt;&lt;/sup&gt; of \(x_1\) and \(x_2\)
computes \(Py\):&lt;/p&gt;

\[Py = A(A^\top A)^{-1}A^\top y = Ab \;\text{ with }\; b = (A^\top
A)^{-1}A^\top y\in\R^2.\]

&lt;p&gt;Thus, if we are given an additional warship’s length and beam as a
vector \(a\in\R^2\), the model’s prediction of its draft will be
\(\langle a, b\rangle\).&lt;/p&gt;

&lt;p&gt;We can implement this idea in simple Python code (&lt;a href=&quot;https://colab.research.google.com/drive/1lPXUxTBDrRC8aZ7MqZZDkvKaUz5Ogh5b&quot; target=&quot;_blank&quot;&gt;Colab
link&lt;/a&gt;):&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Lengths, beams and drafts of 10 warships
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;
187	31	9.4
242	31	9.6
262	32	8.7
216	32	9
195	32	9.7
227	31	11
193	20	5.2
175	17	5.2
&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;lengths&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beams&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;drafts&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loadtxt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;unpack&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lengths&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beams&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;drafts&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;b:&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;model prediction:&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This will print&lt;/p&gt;
&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;b: [-0.00539494  0.34045321]
model prediction: 5.730077087608246
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;So our model would predict a hypothetical warship with length 200m
and beam 20m to have 5.73m of draft.&lt;/p&gt;

&lt;p&gt;Notice that the way we built our model makes it predict a draft of
zero for the (nonsensical) inputs of a warship
of zero meters length or beam. While this seems fine enough in this
case, it’s not in others. A simple way of fixing this is to add an
“intercept” (in machine learning known as “bias”) term: Define
\(\1=(1,\ldots,1)\in\R^n\) and add that as an additional (say, first)
“feature” vector. This turns our model into an affine function of its
data inputs. Doing this in our Python example changes little:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ones_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lengths&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lengths&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beams&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;drafts&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;b:&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;model prediction:&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Result:&lt;/p&gt;

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;b: [ 0.09353128 -0.00580401  0.34027063]
model prediction: 5.738140993529072
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;However, trying to predict crew sizes changes that, see the &lt;a href=&quot;https://colab.research.google.com/drive/1lPXUxTBDrRC8aZ7MqZZDkvKaUz5Ogh5b&quot; target=&quot;_blank&quot;&gt;Colab for
details&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Of course, we can use more than two or three feature vectors as part
of the &lt;em&gt;design matrix&lt;/em&gt; \(A\), as long as they are linearly
independent, which is is typically the case in practice with enough
examples \(n\).&lt;/p&gt;

&lt;p&gt;Using a matrix \(Y\in\R^{n\times m}\) in place of
\(y\in\R^n\) the same math allows us to succinctly treat the
“multivariate” case in which we’re trying to predict more than one
“dependent variable”, e.g. a warship’s draft and the size of its
crew. This is just doing more than one linear regression at once.&lt;/p&gt;

&lt;h3 id=&quot;r2-and-all-that&quot;&gt;\(R^2\) and all that&lt;/h3&gt;

&lt;p&gt;As mentioned above, the distance \(\abs{y - Py}_2\) gives us a sense
of the quality of our model’s predictions when applied to the data we
built it on. The textbooks, being obsessed with element-wise
expressions, call \(\abs{y - Py}_2^2\) the &lt;em&gt;residual sum of squares&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;While this quantity (or a normalized version of it) is a measure of
the error our model produces on the data we know, it doesn’t tell us
if it was our input data that was useful in particular. To quantify
that, we can compare it with a minimal, “inputless” model built from only
the intercept entry, i.e., using \(A_\1 = \1\). The prediction of that model
will be the mean of the data, \(\frac{1}{n}\langle y,
\1\rangle\), and the orthogonal projection on \(\im A_\1 =
\lin\{\1\}\) is \(P_1y = \frac{1}{n}\langle y, \1\rangle\1\). The
squared distance \(\abs{y - P_\1y}_2^2\) of that minimal model’s
predictions from the data is known as the &lt;em&gt;total sum of squares&lt;/em&gt;. It’s
also the unnormalized variance of the data. If our original model used
an intercept term, i.e., \(\1\in\im A\), then \(Py - P_1y\in\im A\)
and therefore \(y - Py \perp Py - P_1y\). Hence, the Pythagorean
identity tells us&lt;/p&gt;

\[\abs{y - P_1y}_2^2 = \abs{y - Py + Py - P_1y}_2^2
  = \abs{y - Py}_2^2 + \abs{Py - P_1y}_2^2.\]

&lt;p&gt;The last term is known somewhat factitiously as the &lt;em&gt;explained sum of
squares&lt;/em&gt; with the idea that it measures deviations from the mean
caused by the data.&lt;/p&gt;

&lt;p&gt;The ratio \(\abs{y - Py}_2^2 / \abs{y - P_1y}_2^2\) is called the
&lt;em&gt;fraction of variance unexplained&lt;/em&gt;, although one has to be careful
with that terminology.
The &lt;em&gt;coefficient of determination&lt;/em&gt; is one minus that number, or&lt;/p&gt;

\[R^2 := 1 - \frac{\abs{y - Py}_2^2}{\abs{y - P_1y}_2^2}
      = \frac{\abs{Py - P_1y}_2^2}{\abs{y - P_1y}_2^2},\]

&lt;p&gt;where the last equality is true if and only if \(\1\in\im A\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Adjustments.&lt;/strong&gt;  Since including more features in our model matrix
\(A\) will make
\(\im A\) a larger subspace of \(\R^n\), the error \(\abs{y -
Py}_2^2\) will be monotonically decreasing and \(R^2\) monotonically
increasing.  While this offers the
opportunity to claim to “explain” more, it might in fact make our
model’s predictions on new inputs worse. Various solutions for this
have been proposed. One somewhat principled approach is to use
“adjusted \(R^2\)”, defined as&lt;/p&gt;

\[\bar{R}^2 = 1 - \frac{\abs{y - Py}_2^2 / (n - p - 1)}{\abs{y -
P_1y}_2^2 / (n - 1)} \le R^2,\]

&lt;p&gt;where \(p\) is the number of features, i.e., \(A\in\R^{n\times
(p+1)}\) if we use an intercept term. This substitutes the unbiased
sample variance and error estimators for their biased versions.&lt;/p&gt;

&lt;p&gt;That’s it for now. We’ll add a proper example from finance in a future
blog post.&lt;/p&gt;
&lt;div class=&quot;footnotes&quot; role=&quot;doc-endnotes&quot;&gt;
  &lt;ol&gt;
    &lt;li id=&quot;fn:1&quot; role=&quot;doc-endnote&quot;&gt;
      &lt;p&gt;In situations with very many feature vectors, computing the
inverse \((A^\top A)^{-1}\) may no longer be the best way of
finding \(b\). Instead, one could try to minimize \(\abs{y-Ab}_2\)
in another way, e.g. via gradient descent. This is how “linear
layers” in machine learning are trained. &lt;a href=&quot;#fnref:1&quot; class=&quot;reversefootnote&quot; role=&quot;doc-backlink&quot;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
  &lt;/ol&gt;
&lt;/div&gt;
</description>
        <pubDate>Wed, 19 Feb 2020 00:00:00 +0000</pubDate>
        <link>https://heiner.ai/blog/2020/02/19/linear-regression.html</link>
        <guid isPermaLink="true">https://heiner.ai/blog/2020/02/19/linear-regression.html</guid>
        
        
        <category>blog</category>
        
      </item>
    
      <item>
        <title>Annuity loans</title>
        <description>&lt;p&gt;&lt;small&gt;Edit June 2023: Via
&lt;a href=&quot;https://twitter.com/HeinrichKuttler/status/1673272830560022529?s=20&quot;&gt;Twitter&lt;/a&gt;,
I found that the same formula I arrive at here has been published in
P. Milanfar, “&lt;em&gt;A Persian Folk Method of Figuring Interest&lt;/em&gt;”, Mathematics
Magazine, vol. 69, no. 5, Dec. 1996 and apparently was known and used
“in the bazaar’s of Iran (and elsewhere)”. The mnemonics in &lt;a href=&quot;https://www.maa.org/sites/default/files/Peyman_Milanfar45123.pdf&quot;&gt;that
paper&lt;/a&gt;
are
\(\textrm{Monthly payment}
=
\frac{1}{\textrm{Number of months}}(\textrm{Principal} + \textrm{Interest})\)
where
\(\textrm{Interest} = \tfrac{1}{2} \textrm{Principal} \cdot
\textrm{Number of years} \cdot \textrm{Annual interest rate}\).
&lt;/small&gt;&lt;/p&gt;

&lt;p&gt;I’m fond of small mental calculation helpers like the &lt;a href=&quot;https://en.wikipedia.org/wiki/Rule_of_72&quot;&gt;rule of
72&lt;/a&gt;. Not that I am good at
mental math (&lt;a href=&quot;https://play.google.com/store/apps/details?id=org.kuettler.mathapp&quot;&gt;I once tried to fix that and got
sidetracked&lt;/a&gt;),
but I am good at spending time contemplating how I’d do it if I was
better at it.&lt;/p&gt;

&lt;p&gt;Another thing I’m not good at is finance. Lack of capital usually
saves me from the worst mistakes, but despite the &lt;a href=&quot;https://www.youtube.com/watch?v=Uwl3-jBNEd4&quot;&gt;brilliant advice
from Ben Felix&lt;/a&gt;, I sometimes
contemplate spending money on real estate. Real estate tends to be
financed with a morgage, which often is a type of annuity loan. What
is an annuity loan and is there a neat rule of thumb for it? Read on
to find out.&lt;/p&gt;

&lt;h2 id=&quot;whats-an-annuity-loan&quot;&gt;What’s an annuity loan?&lt;/h2&gt;

&lt;p&gt;We receive a loan of size \(S_0\) and pay it back. Each period we’ll
pay the same amount&lt;/p&gt;

\[R = T_k + Z_k\]

&lt;p&gt;with a principal repayment \(T_k\) and an interest payment \(Z_k\) for
the \(k\)th payment out of \(n\) total payments.&lt;/p&gt;

&lt;p&gt;The interest payment is going to be a fixed percentage of the
outstanding principal balance and thus \(Z_1 = pS_0,\) where we set
e.g. \(p=0.02\) for a 2% interest rate.&lt;/p&gt;

&lt;h2 id=&quot;so-we-always-pay-the-same-amount-how-much&quot;&gt;So we always pay the same amount. How much?&lt;/h2&gt;

&lt;p&gt;Let’s consider an interest rate of \(p\) and \(n\) periods with one
payment per period. We note that the payment&lt;/p&gt;

\[R = T_1 + pS_0 = T_2 + p(S_0 - T_1),\]

&lt;p&gt;since \(S_0 - T_1\) is the outstanding balance after the first
payment. Hence \(T_2 = (1 + p)T_1\). After \(k\) and \(k+1\) periods&lt;/p&gt;

\[R = T_k + p\Bigl(S_0 - \sum_{j=1}^{k-1} T_j\Bigr)
 = T_{k+1} + p\Bigl(S_0 - \sum_{j=1}^k T_j\Bigr),\]

&lt;p&gt;hence \(T_{k+1} = (1+p)T_k\) and&lt;/p&gt;

\[T_k = (1 + p)^{k-1}T_1.\]

&lt;p&gt;To impose another condition, let’s say we want to fully pay back the
loan after \(n\) periods, i.e.,&lt;/p&gt;

\[S_0 = \sum_{j=1}^{n} T_k = T_1 \sum_{j=1}^{n}(1+p)^{k-1} =
T_1\frac{(1+p)^n - 1}{p},\]

&lt;p&gt;where, as so often, we made use of the sequence of partial sums
\(\sum_{k=0}^{n} q^k = \frac{q^{n+1}-1}{q-1}\) of the geometric
series. Thus we find&lt;/p&gt;

\[R = T_1 + Z_1 = pS_0\frac{1}{(1+p)^n - 1} + pS_0
    = pS_0\frac{(1+p)^n}{(1+p)^n - 1}\]

&lt;p&gt;The regular annuity payment \(R\) is therefore a constant factor of
the loaned amount \(S_0\), the &lt;em&gt;annuity factor&lt;/em&gt;&lt;/p&gt;

\[\af(p, n) = p\frac{(1+p)^n}{(1+p)^n - 1}.\]

&lt;p&gt;Not quite incidentelly, the annuity factor also shows up in formulas
for computing the equivalent annual cost from the net present
value. We won’t go into that here.&lt;/p&gt;

&lt;p&gt;Note that the condition to fully pay back \(S_0\) does not in practice
constrain us very much – if less is paid back, say \(S_1\), we would
do the calculation with \(S_1\) in place of \(S_0\) and add a regular
interest payment of \(p(S_0 - S_1)\).&lt;/p&gt;

&lt;h2 id=&quot;months-and-years&quot;&gt;Months and years&lt;/h2&gt;

&lt;p&gt;Typically we’ll make a monthly payment over many years. This is where
some treatments get confusing and also where banks make a bit of an
extra buck. For \(n\) years and \(p\) interest per year, for our
purposes we’ll just take \(12n\) periods and a monthly interest of
\(\sqrt[12]{1 + p} - 1 = \frac{p}{12} + O(p^2)\). For small \(p\),
e.g. not more than 10%, this is a good approximation. The monthly
payment is then&lt;/p&gt;

\[\frac{p}{12}\frac{(1 + p/12)^{12n}}{(1 + p/12)^{12n} - 1}S_0.\]

&lt;h2 id=&quot;taylored-for-mental-arithmetic&quot;&gt;Taylored for mental arithmetic&lt;/h2&gt;

&lt;p&gt;We started this looking for a simple approximation we can use for
mental arithmetic, like the rule of 72 (it takes \(72/x\) periods for an
investment to double in value if it appreciates \(x\)% per
period). The above isn’t that. The binomial theorem helps:&lt;/p&gt;

\[\Bigl(1 + \frac{p}{12}\Bigr)^{12n}
  = \sum_{k=0}^{12n} \binom{12n}{k} \Bigl(\frac{p}{12}\Bigr)^k
  = 1 + np + \binom{12n}{2}\Bigl(\frac{p}{12}\Bigr)^2 + O(p^3).\]

&lt;p&gt;If we want to forget about the \(p^2\) term as well we end up at&lt;/p&gt;

\[\af(p/12, 12n) \approx \frac{p}{12}\frac{1 + np}{np} = \frac{1 +
np}{12n},\]

&lt;p&gt;which is nice. But not great. A short calculation with the binomial
coefficient \(\binom{12n}{2}\) yields&lt;/p&gt;

\[\binom{12n}{2}\Bigl(\frac{p}{12}\Bigr)^2
  = \frac{(np)^2}{2} - \frac{np^2}{24}.\]

&lt;p&gt;For typical \(n\) and \(p\) (e.g., \(n = 20\) and \(p = 0.02\)) the
second term won’t play any role. With the first term we improve our
approximation to&lt;/p&gt;

\[\af(p/12, 12n)
 \approx \frac{p}{12}\frac{1 + np + (np)^2/2}{np + (np)^2/2}
 = \frac{1}{12n}\frac{1 + np(1 + np/2)}{1 + np/2}
 = \frac{1}{12n}\Bigl(\frac{1}{1 + np/2} + np\Bigr).\]

&lt;p&gt;Now, this is clearly unsuitable. But using the geometric series again
we see that \(\frac{1}{1 + np/2} = 1 - np/2 + (np/2)^2 + O(p^3)\) and
hence&lt;/p&gt;

\[\af(p/12, 12n) \approx \frac{1 + \frac{np}{2}(1 +
\frac{np}{2})}{12n}.\]

&lt;p&gt;This, too, is not too convienient. But if we drop the \((np)^2\) term
we end up with&lt;/p&gt;

\[\af(p/12, 12n) \approx \frac{1 + np/2}{12n}.\]

&lt;p&gt;This isn’t too bad. For slightly larger \(n\) and \(p\) we could also
have taken \(1 + \frac{np}{2} = 1.2\), which would give us \(0.6\)
instead of \(1/2\) in the above formula. Of course we can also do the
division by 12 and arrive at another formula.&lt;/p&gt;

&lt;p&gt;Let’s look at this from a slightly different perspective. A naive,
“interest-free” calculation on what the monthly payment for an \(n\)
year loan of \(S_0\) is would be \(\frac{S_0}{12n}.\)&lt;/p&gt;

&lt;p&gt;Our formula \(\af(p/12, 12n) \approx \frac{1 + np/2}{12n}\) says: &lt;strong&gt;Do
the naive thing, then add x% to the result, where x is “\(n\) times
the interest rate over 2”.&lt;/strong&gt;&lt;/p&gt;

&lt;h2 id=&quot;example&quot;&gt;Example&lt;/h2&gt;

&lt;p&gt;A loan of $400000 with 2% interest over 20 years:&lt;/p&gt;

\[\frac{\$400000}{12\cdot 20} \ \cdot\ \frac{20\cdot 2}{2}\%
  = \$1666 \ \cdot\ 20\% = \$333,\]

&lt;p&gt;so the monthly rate will be \(\$1666 + \$333 = \$2000\). This isn’t
too far from the exact value of \(\af(\sqrt[12]{1.02} - 1, 12n) \cdot
\$400000 = \$2020\).&lt;/p&gt;

&lt;h2 id=&quot;more-numbers&quot;&gt;More numbers&lt;/h2&gt;

&lt;p&gt;The following table compares exact monthly rates as a percentage of
the total loan with our estimate, i.e., the true annuity factor
\(\af(\sqrt[12]{1 + p} - 1, 12n)\) and our approximation
\(\frac{1 + np/2}{12n}\) of it (&lt;strong&gt;bold&lt;/strong&gt;).&lt;/p&gt;

&lt;div class=&quot;centered overflow&quot;&gt;

  &lt;table&gt;
    &lt;thead&gt;
      &lt;tr&gt;
        &lt;th style=&quot;text-align: right&quot;&gt; &lt;/th&gt;
        &lt;th style=&quot;text-align: right&quot;&gt;\(n = 2\)&lt;/th&gt;
        &lt;th style=&quot;text-align: right&quot;&gt;\(n = 5\)&lt;/th&gt;
        &lt;th style=&quot;text-align: right&quot;&gt;\(n = 7\)&lt;/th&gt;
        &lt;th style=&quot;text-align: right&quot;&gt;\(n = 10\)&lt;/th&gt;
        &lt;th style=&quot;text-align: right&quot;&gt;\(n = 15\)&lt;/th&gt;
        &lt;th style=&quot;text-align: right&quot;&gt;\(n = 20\)&lt;/th&gt;
        &lt;th style=&quot;text-align: right&quot;&gt;\(n = 25\)&lt;/th&gt;
        &lt;th style=&quot;text-align: right&quot;&gt;\(n = 30\)&lt;/th&gt;
      &lt;/tr&gt;
    &lt;/thead&gt;
    &lt;tbody&gt;
      &lt;tr&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(p = 0.5\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(4.19\%\)&lt;br /&gt;\(\bf 4.19\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(1.69\%\)&lt;br /&gt;\(\bf 1.69\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(1.21\%\)&lt;br /&gt;\(\bf 1.21\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.85\%\)&lt;br /&gt;\(\bf 0.85\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.58\%\)&lt;br /&gt;\(\bf 0.58\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.44\%\)&lt;br /&gt;\(\bf 0.44\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.35\%\)&lt;br /&gt;\(\bf 0.35\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.30\%\)&lt;br /&gt;\(\bf 0.30\%\)&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(p = 1.0\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(4.21\%\)&lt;br /&gt;\(\bf 4.21\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(1.71\%\)&lt;br /&gt;\(\bf 1.71\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(1.23\%\)&lt;br /&gt;\(\bf 1.23\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.88\%\)&lt;br /&gt;\(\bf 0.88\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.60\%\)&lt;br /&gt;\(\bf 0.60\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.46\%\)&lt;br /&gt;\(\bf 0.46\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.38\%\)&lt;br /&gt;\(\bf 0.38\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.32\%\)&lt;br /&gt;\(\bf 0.32\%\)&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(p = 1.5\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(4.23\%\)&lt;br /&gt;\(\bf 4.23\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(1.73\%\)&lt;br /&gt;\(\bf 1.73\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(1.25\%\)&lt;br /&gt;\(\bf 1.25\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.90\%\)&lt;br /&gt;\(\bf 0.90\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.62\%\)&lt;br /&gt;\(\bf 0.62\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.48\%\)&lt;br /&gt;\(\bf 0.48\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.40\%\)&lt;br /&gt;\(\bf 0.40\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.34\%\)&lt;br /&gt;\(\bf 0.34\%\)&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(p = 2.0\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(4.25\%\)&lt;br /&gt;\(\bf 4.25\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(1.75\%\)&lt;br /&gt;\(\bf 1.75\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(1.28\%\)&lt;br /&gt;\(\bf 1.27\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.92\%\)&lt;br /&gt;\(\bf 0.92\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.64\%\)&lt;br /&gt;\(\bf 0.64\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.51\%\)&lt;br /&gt;\(\bf 0.50\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.42\%\)&lt;br /&gt;\(\bf 0.42\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.37\%\)&lt;br /&gt;\(\bf 0.36\%\)&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(p = 3.0\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(4.30\%\)&lt;br /&gt;\(\bf 4.29\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(1.80\%\)&lt;br /&gt;\(\bf 1.79\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(1.32\%\)&lt;br /&gt;\(\bf 1.32\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.96\%\)&lt;br /&gt;\(\bf 0.96\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.69\%\)&lt;br /&gt;\(\bf 0.68\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.55\%\)&lt;br /&gt;\(\bf 0.54\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.47\%\)&lt;br /&gt;\(\bf 0.46\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.42\%\)&lt;br /&gt;\(\bf 0.40\%\)&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(p = 4.0\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(4.34\%\)&lt;br /&gt;\(\bf 4.33\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(1.84\%\)&lt;br /&gt;\(\bf 1.83\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(1.36\%\)&lt;br /&gt;\(\bf 1.36\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(1.01\%\)&lt;br /&gt;\(\bf 1.00\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.74\%\)&lt;br /&gt;\(\bf 0.72\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.60\%\)&lt;br /&gt;\(\bf 0.58\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.52\%\)&lt;br /&gt;\(\bf 0.50\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.47\%\)&lt;br /&gt;\(\bf 0.44\%\)&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(p = 5.0\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(4.38\%\)&lt;br /&gt;\(\bf 4.38\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(1.88\%\)&lt;br /&gt;\(\bf 1.88\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(1.41\%\)&lt;br /&gt;\(\bf 1.40\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(1.06\%\)&lt;br /&gt;\(\bf 1.04\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.79\%\)&lt;br /&gt;\(\bf 0.76\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.65\%\)&lt;br /&gt;\(\bf 0.62\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.58\%\)&lt;br /&gt;\(\bf 0.54\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.53\%\)&lt;br /&gt;\(\bf 0.49\%\)&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(p = 7.0\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(4.47\%\)&lt;br /&gt;\(\bf 4.46\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(1.97\%\)&lt;br /&gt;\(\bf 1.96\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(1.50\%\)&lt;br /&gt;\(\bf 1.48\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(1.15\%\)&lt;br /&gt;\(\bf 1.13\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.89\%\)&lt;br /&gt;\(\bf 0.85\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.76\%\)&lt;br /&gt;\(\bf 0.71\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.69\%\)&lt;br /&gt;\(\bf 0.62\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.65\%\)&lt;br /&gt;\(\bf 0.57\%\)&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(p = 10.0\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(4.59\%\)&lt;br /&gt;\(\bf 4.58\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(2.10\%\)&lt;br /&gt;\(\bf 2.08\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(1.64\%\)&lt;br /&gt;\(\bf 1.61\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(1.30\%\)&lt;br /&gt;\(\bf 1.25\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(1.05\%\)&lt;br /&gt;\(\bf 0.97\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.94\%\)&lt;br /&gt;\(\bf 0.83\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.88\%\)&lt;br /&gt;\(\bf 0.75\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(0.85\%\)&lt;br /&gt;\(\bf 0.69\%\)&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(p = 20.0\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(5.01\%\)&lt;br /&gt;\(\bf 5.00\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(2.56\%\)&lt;br /&gt;\(\bf 2.50\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(2.12\%\)&lt;br /&gt;\(\bf 2.02\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(1.83\%\)&lt;br /&gt;\(\bf 1.67\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(1.64\%\)&lt;br /&gt;\(\bf 1.39\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(1.57\%\)&lt;br /&gt;\(\bf 1.25\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(1.55\%\)&lt;br /&gt;\(\bf 1.17\%\)&lt;/td&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;\(1.54\%\)&lt;br /&gt;\(\bf 1.11\%\)&lt;/td&gt;
      &lt;/tr&gt;
    &lt;/tbody&gt;
  &lt;/table&gt;

&lt;/div&gt;

&lt;div class=&quot;centered&quot;&gt;
&lt;img src=&quot;/img/afapprox.svg&quot; alt=&quot;AF&quot; style=&quot;width:70%;&quot; /&gt;
&lt;br /&gt;
Our linear approximation \(\frac{1 + np/2}{12n}\), solid, and the true annuity factor
\(\af(\sqrt[12]{1 + p} - 1, 12n)\), dashed, for different number of years \(n\).
&lt;a href=&quot;/img/afapprox.gp&quot;&gt;Gnuplot source&lt;/a&gt;
&lt;/div&gt;

&lt;p&gt;For low interests \(p\) our approximation is rather good. For larger
interests over many years it starts underestimating the true
factor. In this regime using \(0.6\) or higher in place of \(1/2\)
will yield better results.&lt;/p&gt;

&lt;p&gt;This doesn’t mean you should invest in real estate though.&lt;/p&gt;
</description>
        <pubDate>Mon, 19 Aug 2019 23:25:06 +0000</pubDate>
        <link>https://heiner.ai/blog/2019/08/19/annuity-loans.html</link>
        <guid isPermaLink="true">https://heiner.ai/blog/2019/08/19/annuity-loans.html</guid>
        
        
        <category>blog</category>
        
      </item>
    
  </channel>
</rss>
