16 lines
40 KiB
JSON

{
"hash": "9db15bf9ac55734a382c20d347ef1a6d",
"result": {
"engine": "jupyter",
"markdown": "---\ntitle: \"Numbering Numbers: From 0 to ∞\"\ndescription: |\n How do we count an infinitude of numbers?\nformat:\n html:\n html-math-method: katex\ndate: \"2023-11-26\"\ndate-modified: \"2025-07-22\"\ncategories:\n - algebra\n - question-mark function\n - haskell\n---\n\n\n\nThe infinite is replete with paradoxes.\nSome of the best come from comparing sizes of infinite collections.\nFor example, every natural number can be mapped to a (nonnegative) even number and vice versa.\n\n$$\n\\begin{gather*}\n \\N \\rightarrow 2\\N\n \\\\\n n \\mapsto 2n\n \\\\ \\\\\n 0 \\mapsto 0,~ 1 \\mapsto2,~ 2 \\mapsto 4,~ 3 \\mapsto 6,~ 4 \\mapsto 8, ...\n\\end{gather*}\n$$\n\n(For the purposes of this post, $0 \\in \\N, ~ 0 \\notin \\N^+$)\n\nAll even numbers are \"hit\" by this map (by the definition of an even number),\n and no two natural numbers map to the same even number\n (again, more or less by definition, since $2m = 2n$ implies that $m = n$ over $\\N$).\nTherefore, the map is [one-to-one](https://en.wikipedia.org/wiki/Injective_function)\n and [onto](https://en.wikipedia.org/wiki/Surjective_function),\n so the map is a [bijection](https://en.wikipedia.org/wiki/Bijection).\nA consequence is that the map has an inverse, namely by reversing all of the arrows in the above block\n (i.e., the action of halving an even number).\n\nBijections with the natural numbers are easier to understand as a way to place things\n into a linear sequence.\nIn other words, they enumerate \"some sort of item\"; in this case, even numbers.\n\nIn the finite world, a bijection between two things implies that they have the same size.\nIt makes sense to extend the same logic to the infinite world, but there's a catch.\nThe nonnegative even numbers are clearly a strict subset of the natural numbers,\n but by this argument they have the same size.\n\n$$\n\\begin{matrix}\n 2\\N & \\longleftrightarrow & \\N & \\hookleftarrow & 2\\N\n \\\\\n 0 & \\mapsto & \\textcolor{red}0 & \\dashleftarrow & \\textcolor{red}0\n \\\\\n 2 & \\mapsto & 1 & &\n \\\\\n 4 & \\mapsto & \\textcolor{red}2 & \\dashleftarrow & \\textcolor{red}2\n \\\\\n 6 & \\mapsto & 3 & &\n \\\\\n 8 & \\mapsto & \\textcolor{red}4 & \\dashleftarrow & \\textcolor{red}4\n \\\\\n 10 & \\mapsto & 5 & &\n \\\\\n 12 & \\mapsto & \\textcolor{red}6 & \\dashleftarrow & \\textcolor{red}6\n \\\\\n 14 & \\mapsto & 7 & &\n \\\\\n 16 & \\mapsto & \\textcolor{red}8 & \\dashleftarrow & \\textcolor{red}8\n \\\\\n \\vdots & & \\vdots & & \\vdots\n\\end{matrix}\n$$\n\n\nAre we Positive?\n----------------\n\nThe confusion continues if we look at the integers and the naturals.\nIntegers are the natural numbers and their negatives, so it would be intuitive to assume that\n there are twice as many of them as there are naturals (more or less one to account for zero).\nBut since that logic fails for the naturals and the even numbers,\n it fails for the naturals and integers as well.\n\n$$\n\\begin{gather*}\n \\begin{align*}\n \\mathbb{N} &\\rightarrow \\mathbb{Z}\n \\\\\n n &\\mapsto \\left\\{ \\begin{matrix}\n n/2 & n \\text{ even}\n \\\\\n -(n+1)/2 & n \\text{ odd}\n \\end{matrix} \\right.\n \\end{align*}\n \\\\ \\\\\n 0 \\mapsto 0,\\quad 2 \\mapsto 1, \\quad 4 \\mapsto 2, \\quad 6 \\mapsto 3, \\quad 8 \\mapsto 4,~...\n \\\\\n 1 \\mapsto -1, \\quad 3 \\mapsto -2, \\quad 5 \\mapsto -3, \\quad 7 \\mapsto -4, \\quad 9 \\mapsto -5,~...\n\\end{gather*}\n$$\n\nOr, in Haskell[^1]:\n\n[^1]: That is, if you cover your eyes and pretend that `undefined` will never happen,\n and if you ignore that `Int` is bounded, unlike `Integer`.\n\n::: {#775b525e .cell execution_count=3}\n``` {.haskell .cell-code}\ntype Nat = Int\n\nlistIntegers :: Nat -> Int\nlistIntegers n\n | n < 0 = undefined\n | even n = n `div` 2\n | otherwise = -(n + 1) `div` 2\n```\n:::\n\n\nIn other words, this map sends even numbers to the naturals (the inverse of the doubling map)\n and the odds to the negatives.\nThe same arguments about the bijective nature of this map apply as before, and so the paradox persists,\n since naturals are also a strict subset of integers.\n\n\n### Rational Numbers\n\nRationals are a bit worse.\nTo make things a little easier, let's focus on the positive rationals (i.e., fractions excluding 0).\nUnlike the integers, there is no obvious \"next rational\" after (or even before) 1.\nIf there were, we could follow it with its reciprocal, like how an integer is followed\n by its negative in the map above.\n\nOn the other hand, the integers provide a sliver of hope that listing all rational numbers is possible.\nIntegers can be defined as pairs of natural numbers, along with a way of considering two pairs equal.\n\n$$\n\\begin{gather*}\n -1 = (0,1) \\sim_\\Z (1,2) \\sim_\\Z (2,3) \\sim_\\Z (3,4) \\sim_\\Z ...\n \\\\[10pt]\n (a,b) \\sim_\\mathbb{Z} (c,d) \\iff a+d = b+c \\quad a,b,c,d \\in \\mathbb{N}\n \\\\[10pt]\n \\mathbb{Z} := ( \\mathbb{N} \\times \\mathbb{N} ) / \\sim_\\mathbb{Z}\n\\end{gather*}\n$$\n\n::: {#97b6db11 .cell execution_count=4}\n``` {.haskell .cell-code}\nintEqual :: (Nat, Nat) -> (Nat, Nat) -> Bool\nintEqual (a, b) (c, d) = a + d == b + c\n```\n:::\n\n\nThis relation is the same as saying $a - b = c - d$ (i.e., that -1 = 0 - 1, etc.),\n but has the benefit of not requiring subtraction to be defined.\nThis is all the better, since, as grade-schoolers are taught, subtracting a larger natural number\n from a smaller one is impossible.\n\nThe same equivalence definition exists for positive rationals.\nIt is perhaps more familiar, because of the emphasis placed on simplifying fractions when learning them.\nWe can [cross-multiply](https://en.wikipedia.org/wiki/Cross-multiplication) fractions to get\n a similar equality condition to the one for integers.\n\n$$\n\\begin{gather*}\n {1 \\over 2} = (1,2) \\sim_\\mathbb{Q} \\overset{2/4}{(2,4)} \\sim_\\mathbb{Q}\n \\overset{3/6}{(3,6)} \\sim_\\mathbb{Q} \\overset{4/8}{(4,8)} \\sim_\\mathbb{Q} ...\n \\\\ \\\\\n (a,b) \\sim_\\mathbb{Q} (c,d) \\iff ad = bc \\quad a,b,c,d \\in \\mathbb{N}^+\n \\\\ ~ \\\\\n \\mathbb{Q^+} := ( \\mathbb{N^+} \\times \\mathbb{N^+} ) / \\sim_\\mathbb{Q}\n\\end{gather*}\n$$\n\n::: {#4c4d2c94 .cell execution_count=5}\n``` {.haskell .cell-code}\nratEqual :: (Nat, Nat) -> (Nat, Nat) -> Bool\nratEqual (a, b) (c, d) = a * d == b * c\n```\n:::\n\n\nWe specify that neither element of the pair can be zero, so this excludes divisions by zero\n (and the especially tricky case of 0/0, which would be equal to all fractions).\nEffectively, this just replaces where addition appears in the integer equivalence with multiplication.\n\n\n### Eliminating Repeats\n\nNaively, to tackle both of these cases, we might consider enumerating pairs of natural numbers.\nWe order them by sums and break ties by sorting on the first index.\n\n::: {#aa044caa .cell execution_count=6}\n``` {.haskell .cell-code}\n-- All pairs of natural numbers that sum to n\nlistPairs :: Nat -> [(Nat, Nat)]\nlistPairs n = [ (k, n - k) | k <- [0..n] ]\n\n-- \"Triangular\" enumeration of all pairs of positive integers\nallPairs :: [(Nat, Nat)]\nallPairs = concatMap listPairs [0..]\n\n-- Use a natural number to index the enumeration of all pairs\nallPairsMap :: Nat -> (Nat, Nat)\nallPairsMap n = allPairs !! n\n```\n:::\n\n\n::: {#6143624a .cell .plain execution_count=7}\n``` {.haskell .cell-code code-fold=\"true\"}\npairEnumeration = columns (\\(_, f) v -> f v) (\\(l, _) -> Headed l) [\n (\"Index\", show . fst),\n (\"Pair (a, b)\", show . snd),\n (\"Sum (a + b)\", show . uncurry (+) . snd),\n (\"Integer (a - b)\", show . uncurry (-) . snd),\n (\"Rational (a+1 / b+1)\", (\\(a, b) -> show (a + 1) ++ \"/\" ++ show (b + 1)) . snd)\n ]\n\nrenderTable (rmap stringCell pairEnumeration) $ take 10 $ zip [0..] allPairs\n```\n\n::: {.cell-output .cell-output-display}\n```{=html}\n<table class=\"\">\n <thead>\n <tr>\n <th>\n Index\n </th>\n <th>\n Pair (a, b)\n </th>\n <th>\n Sum (a + b)\n </th>\n <th>\n Integer (a - b)\n </th>\n <th>\n Rational (a+1 / b+1)\n </th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>\n 0\n </td>\n <td>\n (0,0)\n </td>\n <td>\n 0\n </td>\n <td>\n 0\n </td>\n <td>\n 1/1\n </td>\n </tr>\n <tr>\n <td>\n 1\n </td>\n <td>\n (0,1)\n </td>\n <td>\n 1\n </td>\n <td>\n -1\n </td>\n <td>\n 1/2\n </td>\n </tr>\n <tr>\n <td>\n 2\n </td>\n <td>\n (1,0)\n </td>\n <td>\n 1\n </td>\n <td>\n 1\n </td>\n <td>\n 2/1\n </td>\n </tr>\n <tr>\n <td>\n 3\n </td>\n <td>\n (0,2)\n </td>\n <td>\n 2\n </td>\n <td>\n -2\n </td>\n <td>\n 1/3\n </td>\n </tr>\n <tr>\n <td>\n 4\n </td>\n <td>\n (1,1)\n </td>\n <td>\n 2\n </td>\n <td>\n 0\n </td>\n <td>\n 2/2\n </td>\n </tr>\n <tr>\n <td>\n 5\n </td>\n <td>\n (2,0)\n </td>\n <td>\n 2\n </td>\n <td>\n 2\n </td>\n <td>\n 3/1\n </td>\n </tr>\n <tr>\n <td>\n 6\n </td>\n <td>\n (0,3)\n </td>\n <td>\n 3\n </td>\n <td>\n -3\n </td>\n <td>\n 1/4\n </td>\n </tr>\n <tr>\n <td>\n 7\n </td>\n <td>\n (1,2)\n </td>\n <td>\n 3\n </td>\n <td>\n -1\n </td>\n <td>\n 2/3\n </td>\n </tr>\n <tr>\n <td>\n 8\n </td>\n <td>\n (2,1)\n </td>\n <td>\n 3\n </td>\n <td>\n 1\n </td>\n <td>\n 3/2\n </td>\n </tr>\n <tr>\n <td>\n 9\n </td>\n <td>\n (3,0)\n </td>\n <td>\n 3\n </td>\n <td>\n 3\n </td>\n <td>\n 4/1\n </td>\n </tr>\n </tbody>\n</table>\n```\n:::\n:::\n\n\nThis certainly works to show that naturals and pairs of naturals can be put into bijection,\n but it when interpreting the results as integers or rationals, we double-count several of them.\nThis is easy to see in the case of the integers, but it will also happen in the rationals.\nFor example, the pair (3, 5) would correspond to 4/6 = 2/3, which has already been counted.\n\nIncidentally, Haskell comes with a function called `nubBy`.\nThis function eliminates duplicates according to another function of our choosing.\nWe can also just implement it ourselves and use it to create a naive enumeration of integers and rationals,\n based on the equalities defined earlier:\n\n::: {#7017b14d .cell execution_count=8}\n``` {.haskell .cell-code}\nnubBy :: (a -> a -> Bool) -> [a] -> [a]\nnubBy f = nubBy' [] where\n nubBy' ys [] = []\n nubBy' ys (z:zs)\n -- Ignore this element, something equivalent is in ys\n | any (f z) ys = nubBy' ys zs\n -- Append this element to the result and our internal list\n | otherwise = z:nubBy' (z:ys) zs\n\nallIntegers :: [(Nat, Nat)]\n-- Remove duplicates under integer equality\nallIntegers = nubBy intEqual allPairs\n\nallIntegersMap :: Nat -> (Nat, Nat)\nallIntegersMap n = allIntegers !! n\n\nallRationals :: [(Nat, Nat)]\n-- Add 1 to the numerator and denominator to get rid of 0,\n-- then remove duplicates under fraction equality\nallRationals = nubBy ratEqual $ map (\\(a,b) -> (a+1, b+1)) allPairs\n\nallRationalsMap :: Nat -> (Nat, Nat)\nallRationalsMap n = allRationals !! n\n```\n:::\n\n\nFor completeness's sake, the resulting pairs of each map are as follows\n\n::: {#95e58f2c .cell .plain execution_count=9}\n``` {.haskell .cell-code code-fold=\"true\"}\ncodeCell = htmlCell . Html.code . Html.string\n\nshowAsInteger p@(a,b) = show p ++ \" = \" ++ show (a - b)\nshowAsRational' p@(a,b) = show a ++ \"/\" ++ show b\nshowAsRational p@(a,b) = show p ++ \" = \" ++ showAsRational' p\n\nmapEnumeration = columns (\\(_, f) v -> f v) (\\(l, _) -> Headed l) [\n (stringCell \"n\", stringCell . show),\n (codeCell \"allIntegersMap n\",\n stringCell . showAsInteger . allIntegersMap),\n (codeCell \"allRationalsMap n\",\n stringCell . showAsRational . allRationalsMap)\n ]\n\nrenderTable mapEnumeration [0..9]\n```\n\n::: {.cell-output .cell-output-display}\n```{=html}\n<table class=\"\">\n <thead>\n <tr>\n <th>\n n\n </th>\n <th>\n <code>\n allIntegersMap n\n </code>\n </th>\n <th>\n <code>\n allRationalsMap n\n </code>\n </th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>\n 0\n </td>\n <td>\n (0,0) = 0\n </td>\n <td>\n (1,1) = 1/1\n </td>\n </tr>\n <tr>\n <td>\n 1\n </td>\n <td>\n (0,1) = -1\n </td>\n <td>\n (1,2) = 1/2\n </td>\n </tr>\n <tr>\n <td>\n 2\n </td>\n <td>\n (1,0) = 1\n </td>\n <td>\n (2,1) = 2/1\n </td>\n </tr>\n <tr>\n <td>\n 3\n </td>\n <td>\n (0,2) = -2\n </td>\n <td>\n (1,3) = 1/3\n </td>\n </tr>\n <tr>\n <td>\n 4\n </td>\n <td>\n (2,0) = 2\n </td>\n <td>\n (3,1) = 3/1\n </td>\n </tr>\n <tr>\n <td>\n 5\n </td>\n <td>\n (0,3) = -3\n </td>\n <td>\n (1,4) = 1/4\n </td>\n </tr>\n <tr>\n <td>\n 6\n </td>\n <td>\n (3,0) = 3\n </td>\n <td>\n (2,3) = 2/3\n </td>\n </tr>\n <tr>\n <td>\n 7\n </td>\n <td>\n (0,4) = -4\n </td>\n <td>\n (3,2) = 3/2\n </td>\n </tr>\n <tr>\n <td>\n 8\n </td>\n <td>\n (4,0) = 4\n </td>\n <td>\n (4,1) = 4/1\n </td>\n </tr>\n <tr>\n <td>\n 9\n </td>\n <td>\n (0,5) = -5\n </td>\n <td>\n (1,5) = 1/5\n </td>\n </tr>\n </tbody>\n</table>\n```\n:::\n:::\n\n\nNote that the tuples produced by `allIntegers`, when interpreted as integers, happen to coincide\n with the earlier enumeration given by `listIntegers`.\n\n\nTree of Fractions\n-----------------\n\nThere's an entirely separate structure which contains all rationals in least terms.\nIt relies on an operation between two fractions called the *mediant*.\nFor two rational numbers in least terms *p* and *q*, such that *p* < *q*, the mediant is designated *p* ⊕ *q* and will:\n\n1. also be in least terms (with some exceptions, see below),\n2. be larger than *p*, and\n3. be smaller than *q*\n\n$$\n\\begin{gather*}\n p = {a \\over b} < {c \\over d} = q, \\quad \\gcd(a,b) = \\gcd(c,d) = 1\n \\\\ \\\\\n p < p \\oplus q < q \\quad \\phantom{\\gcd(a+c, b+d) = 1}\n \\\\ \\\\\n {a \\over b} < {a+c \\over b+d} < {c \\over d}, \\quad \\gcd(a+c, b+d) = 1\n\\end{gather*}\n$$\n\nWe know our sequence of rationals starts with 1/1, 1/2, and 2/1.\nIf we start as before with 1/1 and want to get the other quantities,\n then we can take its mediants with 0/1 and 1/0, respectively\n (handwaving the fact that the latter isn't a legitimate fraction).\n\n$$\n\\begin{align*}\n && && \\large{1 \\over 1} && &&\n \\\\\n { \\oplus {0 \\over 1} } && \\large{/} && && \\large{\\backslash} ~ && \\oplus {1 \\over 0}\n \\\\\n && \\large{1 \\over 2} && && \\large{2 \\over 1} &&\n\\end{align*}\n$$\n\nWe might try continuing this pattern by doing the same thing to 1/2.\nWe can take its mediant with 0/1 to get 1/3.\nUnfortunately, the mediant of 1/2 and 1/0 is 2/2 (as is the mediant of 2/1 with 0/1),\n which isn't in least terms, and has already appeared as 1/1.\n\nWe could try another fraction that's appeared in the tree.\nUnfortunately, 2/1 suffers from the same issue as 1/0 -- 1/2 ⊕ 2/1 = 3/3, which is\n the same quantity as before, despite both fractions being in least terms.\nOn the other hand, 1/2 ⊕ 1/1 = 2/3, which is in least terms.\nSimilarly, 2/1 ⊕ 1/1 is 3/2, its reciprocal.\n\n$$\n\\begin{align*}\n && && \\large{1 \\over 2} && &&\n \\\\\n { \\oplus {0 \\over 1} } && \\large{/} && && \\large{\\backslash} ~ && \\oplus {1 \\over 1}\n \\\\\n && \\large{1 \\over 3} && && \\large{2 \\over 3} &&\n\\end{align*}\n\\qquad \\qquad\n\\begin{align*}\n && && \\large{2 \\over 1} && &&\n \\\\\n { \\oplus {1 \\over 1} } && \\large{/} && && \\large{\\backslash} ~ && \\oplus {1 \\over 0}\n \\\\\n && \\large{3 \\over 2} && && \\large{3 \\over 1} &&\n\\end{align*}\n$$\n\nThe trick is to notice that a step to the left \"updates\" what the next step to the right looks like.\nSteps to the right behave symmetrically.\nFor example, in the row we just generated, the left child of 2/3 is its mediant with 1/2,\n its right child is its mediant with 1/1.\n\nContinuing this iteration ad infinitum forms the\n [Stern-Brocot tree](https://en.wikipedia.org/wiki/Stern%E2%80%93Brocot_tree).\nA notable feature of this is that it is a\n [binary search tree](https://en.wikipedia.org/wiki/Binary_search_tree) (of infinite height).\nThis means that for any node, the value at the node is greater than all values in the left subtree\n and less than all values in the right subtree.\n\n![](./stern-brocot_tree.png)\n\nThere's a bit of a lie in presenting the tree like this.\nAs a binary tree, it's most convenient to show the nodes spaced evenly, but the distance between\n 1/1 and 2/1 is not typically seen as the same as the distance between 1/1 and 1/2.\n\nWe can implement this in Haskell using `Data.Tree`.\nThis package actually lets you describe trees with any number of child nodes,\n but we only need two for the sake of the Stern-Brocot tree.\n\n::: {#688b980d .cell execution_count=10}\n``` {.haskell .cell-code}\nimport Data.Tree\n\n-- Make a tree by applying the function `make` to each node\n-- Start with the root value (1, 1), along with\n-- its left and right steps, (0, 1) and (1, 0)\nsternBrocot = unfoldTree make ((1,1), (0,1), (1,0)) where\n -- Place the first value in the tree, then describe the next\n -- values for `make` in a list:\n make (v@(vn, vd), l@(ln, ld), r@(rn, rd))\n = (v, [\n -- the left value, and its left (unchanged) and right steps...\n ((ln + vn, ld + vd), l, v),\n -- and the right value, and its left and right (unchanged) steps\n ((vn + rn, vd + rd), v, r)\n ])\n```\n:::\n\n\n### Cutting the Tree Down\n\nWe're halfway there. All that remains is to read off every value in the tree as a sequence.\nPerhaps the most naive way would be to read off by always following the left or right child.\nUnfortunately, these give some fairly dull sequences.\n\n::: {#5911816b .cell layout-ncol='2' execution_count=11}\n``` {.haskell .cell-code}\ntreePath :: [Int] -> Tree a -> [a]\ntreePath xs (Node y ys)\n -- If we don't have any directions (xs), or the node\n -- has no children (ys), then there's nowhere to go\n | null xs || null ys = [y]\n -- Otherwise, go down subtree \"x\", then recurse with that tree\n -- and the rest of the directions (xs)\n | otherwise = y:treePath (tail xs) (ys !! head xs)\n\n-- Always go left (child 0)\n-- i.e., numbers with numerator 1\nmapM_ print $ take 10 $ treePath (repeat 0) sternBrocot\n\n-- Always go right (child 1)\n-- i.e., numbers with denominator 1\nmapM_ print $ take 10 $ treePath (repeat 1) sternBrocot\n```\n\n::: {.cell-output .cell-output-display}\n```\n(1,1)\n(1,2)\n(1,3)\n(1,4)\n(1,5)\n(1,6)\n(1,7)\n(1,8)\n(1,9)\n(1,10)\n```\n:::\n\n::: {.cell-output .cell-output-display}\n```\n(1,1)\n(2,1)\n(3,1)\n(4,1)\n(5,1)\n(6,1)\n(7,1)\n(8,1)\n(9,1)\n(10,1)\n```\n:::\n:::\n\n\nRather than by following paths in the tree, we can instead do a breadth-first search.\nIn other words, we read off each row individually, in order.\nThis gives us our sequence of rational numbers with no repeats.\n\n$$\n\\begin{gather*}\n \\begin{align*}\n \\mathbb{N^+}& ~\\rightarrow~ \\mathbb{Q}\n \\\\\n n & ~\\mapsto~ \\text{bfs}[n]\n \\end{align*}\n \\\\ \\\\\n 1 \\mapsto 1/1,~ \\\\\n 2 \\mapsto 1/2,\\quad 3 \\mapsto 2/1,~ \\\\\n 4 \\mapsto 1/3,\\quad 5 \\mapsto 2/3, \\quad 6 \\mapsto 3/2, \\quad 7 \\mapsto 3/1,~ ...\n\\end{gather*}\n$$\n\nFor convenience, this enumeration is given starting from 1 rather than from 0.\nThis numbering makes it clearer that each row starts with a power of 2,\n since the structure is a binary tree, and the complexity doubles with each row.\nThe enumeration could just as easily start from 0 by starting with $\\N$,\n then getting to $\\N^+$ with $n \\mapsto n+1$.\n\nWe can also write a breadth-first search in Haskell, for posterity:\n\n::: {#91920684 .cell execution_count=12}\n``` {.haskell .cell-code}\nbfs :: Tree a -> [a]\nbfs (Node root children) = bfs' root children where\n -- Place the current node in the list\n bfs' v [] = [v]\n -- Pluck one node off our list of trees, then recurse with\n -- the rest, along with that node's children\n bfs' v ((Node y ys):xs) = v:bfs' y (xs ++ ys)\n\nsternBrocotRationals = bfs sternBrocot\n\nmapM_ putStrLn $ take 10 $ map showAsRational sternBrocotRationals\n```\n\n::: {.cell-output .cell-output-display}\n```\n(1,1) = 1/1\n(1,2) = 1/2\n(2,1) = 2/1\n(1,3) = 1/3\n(2,3) = 2/3\n(3,2) = 3/2\n(3,1) = 3/1\n(1,4) = 1/4\n(2,5) = 2/5\n(3,5) = 3/5\n```\n:::\n:::\n\n\nThe entries in this enumeration have already been given.\n\n\n### Another Tree\n\nAnother tree of fractions to consider is the tree of binary fractions.\nThese fractions simply consist of odd numbers divided by powers of two.\nThe most convenient way to organize these into a tree is to keep denominators equal\n if the nodes have the same depth from the root.\nWe also stipulate that we arrange the nodes as a binary search tree, like the Stern-Brocot tree.\n\nThe tree starts from 1/1 as before.\nIts children have denominator 2, so we have 1/2 to the left and 3/2 to the right.\nThis is equivalent to subtracting 1/2 for the left step and adding 1/2 for the right step.\nAt the next layer, we want fractions with denominator 1/4, and do similarly.\nIn terms of adding and subtracting, we just use 1/4 instead of 1/2.\n\n![](./dyadic_fraction_tree.png)\n\nWe can describe this easily in Haskell:\n\n::: {#555c1dba .cell execution_count=13}\n``` {.haskell .cell-code}\n-- Start with 1/1 (i.e., (1, 1))\nbinFracTree = unfoldTree make (1,1) where\n -- Place the first value in the tree, then describe the next\n -- values for `make` in a list:\n make v@(vn, vd)\n = (v, [\n -- double the numerator and denominator, then subtract 1 from the numerator\n (2*vn - 1, 2*vd),\n -- same, but add 1 to the numerator instead\n (2*vn + 1, 2*vd)\n ])\n```\n:::\n\n\nThe entries of this tree have an additional interpretation when converted to their binary expansions.\nThese fractions always terminate in a \"1\" in binary, but ignoring this final entry, starting from the root\n and following \"left\" for 0 and \"right\" for 1 places us at that fraction in the tree.\nIn other words, the binary expansions encode the path from the root to the node.\n\n![](./binary_expansion_tree.png)\n\n\nWhy Bother?\n-----------\n\nThe tree of binary fractions and the Stern-Brocot tree are both infinite binary search trees,\n so we might imagine overlaying one tree over the other, pairing up the individual entries.\n\n![](./question_mark_tree.png)\n\nIn Haskell, we can pair up entries recursively:\n\n::: {#82577de7 .cell execution_count=14}\n``` {.haskell .cell-code}\nzipTree :: Tree a -> Tree b -> Tree (a,b)\n-- Pair the values in the nodes together, then recurse with the child trees\nzipTree (Node x xs) (Node y ys) = Node (x,y) $ zipWith zipTree xs ys\n\nbinarySBTree = zipTree sternBrocot binFracTree\n```\n:::\n\n\nConveniently, both left subtrees of the root fall in the interval (0, 1).\nIt also pairs up 1 and 1/2 with themselves.\nDoing so establishes a bijection between the rationals and the binary rationals in that interval.\nRationals are more continuous than integers, so it might be of some curiosity to plot this function.\nWe only have to look at a square over the unit interval. Doing so reveals a curious shape:\n\n::: {#66c88259 .cell layout-ncol='2' execution_count=15}\n``` {.haskell .cell-code code-fold=\"true\"}\nimport Data.Tuple (swap)\nimport Data.List (sort)\nimport Data.Bifunctor (bimap, first)\n\nleftSubtree (Node _ (x:_)) = x\n\n-- Divide entries of the (zipped) trees\n(</>) (a,b) = fromIntegral a / fromIntegral b :: Double\nbinarySBDoubles n = take n $ map (bimap (</>) (</>)) $ bfs $ leftSubtree binarySBTree\n\n(MPL.tightLayout <>) $ uncurry MPL.plot $ unzip $ sort $ map swap $ binarySBDoubles 250\n(MPL.tightLayout <>) $ uncurry MPL.plot $ unzip $ sort $ binarySBDoubles 250\n```\n\n::: {.cell-output .cell-output-display}\n![Binary rationals on the x-axis, rationals on the y-axis](index_files/figure-html/cell-15-output-1.svg){}\n:::\n\n::: {.cell-output .cell-output-display}\n![Rationals on the x-axis, binary rationals on the y-axis](index_files/figure-html/cell-15-output-2.svg){}\n:::\n:::\n\n\nThe plot on the right which maps the rationals to the binary rationals is known as\n [Minkowski's question mark function](https://en.wikipedia.org/wiki/Minkowski%27s_question-mark_function).\nNotice that this function is nearly 1/2 for values near 1/2\n (nearly 1/4 for values near 1/3, nearly 1/8 for values near 1/4, etc.).\n\n\n### I'm Repeating Myself\n\nThe inverse question mark map (which I'll call ¿ for short), besides mapping binary rationals to rationals,\n has an interesting relationship with other rational numbers.\nRecall that we only defined the function in terms of fractions\n which happen to have finite binary expansions.\nThose with infinite binary expansions, such as 1/3 (and indeed, any fraction whose denominator\n isn't a power of 2) aren't defined.\n\n$$\n\\begin{gather*}\n {1 \\over 2} = 0.1_2\n \\\\\n {1 \\over 3} = 0.\\overline{01} = 0.\\textcolor{red}{01}\\textcolor{green}{01}\\textcolor{blue}{01}...\n \\\\\n {1 \\over 4} = 0.01_2\n \\\\\n {1 \\over 5} = 0.\\overline{0011} = 0.\\textcolor{red}{0011}\\textcolor{green}{0011}\\textcolor{blue}{0011}...\n \\\\\n \\vdots\n\\end{gather*}\n$$\n\nWe can persevere if we continue to interpret the binary strings as a path in the tree.\nThis means that for 1/3, we go left initially, then alternate between going left and right.\nAs we do so, let's take note of the values we pass along the way:\n\n::: {#a0b1bf2f .cell execution_count=16}\n``` {.haskell .cell-code}\n-- Follow the path described by the binary expansion of 1/3\noneThirdPath = treePath (0:cycle [0,1]) $ zipTree sternBrocot binFracTree\n```\n:::\n\n\n::: {#f54ff78f .cell .plain execution_count=17}\n``` {.haskell .cell-code code-fold=\"true\"}\ntrimTo n x = if length x > n then \"(too big to show)\" else x\n\ntreePathColumns = columns (\\(_, f) v -> f v) (\\(l, _) -> Headed l) [\n (stringCell \"n\",\n stringCell . fromEither . fmap show),\n (stringCell \"Binary fraction\",\n stringCell . fromEither . fmap (trimTo 10 . showAsRational' . snd . (oneThirdPath !!))),\n (stringCell \"Binary fraction (decimal)\",\n stringCell . fromEither . fmap (show . (</>) . snd . (oneThirdPath !!))),\n (stringCell \"Stern-Brocot rational\",\n stringCell . fromEither . fmap (trimTo 10 . showAsRational' . fst . (oneThirdPath !!))),\n (stringCell \"Stern-Brocot rational (decimal)\",\n stringCell . fromEither . fmap (show . (</>) . fst . (oneThirdPath !!)))\n ] where\n fromEither = either id id\n\nrenderTable treePathColumns (map Right [0..8] ++ [Left \"...\", Right 100, Left \"...\"])\n```\n\n::: {.cell-output .cell-output-display}\n```{=html}\n<table class=\"\">\n <thead>\n <tr>\n <th>\n n\n </th>\n <th>\n Binary fraction\n </th>\n <th>\n Binary fraction (decimal)\n </th>\n <th>\n Stern-Brocot rational\n </th>\n <th>\n Stern-Brocot rational (decimal)\n </th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>\n 0\n </td>\n <td>\n 1/1\n </td>\n <td>\n 1.0\n </td>\n <td>\n 1/1\n </td>\n <td>\n 1.0\n </td>\n </tr>\n <tr>\n <td>\n 1\n </td>\n <td>\n 1/2\n </td>\n <td>\n 0.5\n </td>\n <td>\n 1/2\n </td>\n <td>\n 0.5\n </td>\n </tr>\n <tr>\n <td>\n 2\n </td>\n <td>\n 1/4\n </td>\n <td>\n 0.25\n </td>\n <td>\n 1/3\n </td>\n <td>\n 0.3333333333333333\n </td>\n </tr>\n <tr>\n <td>\n 3\n </td>\n <td>\n 3/8\n </td>\n <td>\n 0.375\n </td>\n <td>\n 2/5\n </td>\n <td>\n 0.4\n </td>\n </tr>\n <tr>\n <td>\n 4\n </td>\n <td>\n 5/16\n </td>\n <td>\n 0.3125\n </td>\n <td>\n 3/8\n </td>\n <td>\n 0.375\n </td>\n </tr>\n <tr>\n <td>\n 5\n </td>\n <td>\n 11/32\n </td>\n <td>\n 0.34375\n </td>\n <td>\n 5/13\n </td>\n <td>\n 0.38461538461538464\n </td>\n </tr>\n <tr>\n <td>\n 6\n </td>\n <td>\n 21/64\n </td>\n <td>\n 0.328125\n </td>\n <td>\n 8/21\n </td>\n <td>\n 0.38095238095238093\n </td>\n </tr>\n <tr>\n <td>\n 7\n </td>\n <td>\n 43/128\n </td>\n <td>\n 0.3359375\n </td>\n <td>\n 13/34\n </td>\n <td>\n 0.38235294117647056\n </td>\n </tr>\n <tr>\n <td>\n 8\n </td>\n <td>\n 85/256\n </td>\n <td>\n 0.33203125\n </td>\n <td>\n 21/55\n </td>\n <td>\n 0.38181818181818183\n </td>\n </tr>\n <tr>\n <td>\n ...\n </td>\n <td>\n ...\n </td>\n <td>\n ...\n </td>\n <td>\n ...\n </td>\n <td>\n ...\n </td>\n </tr>\n <tr>\n <td>\n 100\n </td>\n <td>\n (too big to show)\n </td>\n <td>\n 0.3333333333333333\n </td>\n <td>\n (too big to show)\n </td>\n <td>\n 0.3819660112501052\n </td>\n </tr>\n <tr>\n <td>\n ...\n </td>\n <td>\n ...\n </td>\n <td>\n ...\n </td>\n <td>\n ...\n </td>\n <td>\n ...\n </td>\n </tr>\n </tbody>\n</table>\n```\n:::\n:::\n\n\n::: {#9f7b9346 .cell layout-ncol='2' execution_count=18}\n``` {.haskell .cell-code code-fold=\"true\"}\nconvergentsOneThird = map ((</>) . snd) oneThirdPath\nconvergentsSBNumber = map ((</>) . fst) oneThirdPath\n\nplotSequence n = uncurry MPL.plot . unzip . take n . zip ([0..] :: [Int])\n\n(MPL.tightLayout <>) $ plotSequence 20 convergentsOneThird\n(MPL.tightLayout <>) $ plotSequence 20 convergentsSBNumber\n```\n\n::: {.cell-output .cell-output-display}\n![Binary convergents of 1/3](index_files/figure-html/cell-18-output-1.svg){}\n:::\n\n::: {.cell-output .cell-output-display}\n![¿ applied to binary convergents of 1/3, which also appear to converge](index_files/figure-html/cell-18-output-2.svg){}\n:::\n:::\n\n\nBoth sequences appear to converge to a number, with the binary fractions obviously converging to 1/3.\nThe rationals from the Stern-Brocot don't appear to be converging to a repeating decimal.\nLooking closer, the numerators and denominators of the fractions appear to come from the Fibonacci numbers.\nIn fact, the quantity that the fractions approach is $2 - \\varphi$, where φ is the golden ratio.\nThis number is the root of the polynomial $x^2 - 3x + 1$.\n\nIn fact, all degree 2 polynomials have roots that are encoded by a repeating path in the Stern-Brocot tree.\nPut another way, ¿ can be extended to map rationals other than binary fractions to quadratic roots\n (and ? maps quadratic roots to rational numbers).\nThis is easier to understand when writing the quantity as its\n [continued fraction expansion](https://en.wikipedia.org/wiki/Continued_fraction),\n but that's an entirely separate discussion.\n\nEither way, it tells us something interesting: not only can all rational numbers be enumerated,\n but so can quadratic *irrationals*.\n\n\n### The Other Side\n\nI'd like to briefly digress from talking about enumerations and mention the right subtree.\nThe question mark function, as defined here, is only defined on numbers between 0 and 1\n (and even then, technically only rational numbers).\nAccording to Wikipedia's definition, the question mark function is quasi-periodic --\n $?(x + 1) = ?(x) + 1$.\nOn the other hand, according to the definition by pairing up the two trees,\n rationals greater than 1 get mapped to binary fractions between 1 and 2.\n\n::: {#fig-question-mark-linlog .cell layout-ncol='2' execution_count=19}\n``` {.haskell .cell-code code-fold=\"true\"}\nbinarySBDoublesAll n = take n $ map (bimap (</>) (</>)) $ bfs binarySBTree\n\n(MPL.tightLayout <>) $ uncurry MPL.plot $\n unzip $ sort $ binarySBDoublesAll 250\n(MPL.tightLayout <>) $ uncurry MPL.plot $\n unzip $ map (first log) $ sort $ binarySBDoublesAll 250\n```\n\n::: {.cell-output .cell-output-display}\n![linear x-axis](index_files/figure-html/fig-question-mark-linlog-output-1.svg){#fig-question-mark-linlog-1}\n:::\n\n::: {.cell-output .cell-output-display}\n![(base 2)-logarithmic x-axis](index_files/figure-html/fig-question-mark-linlog-output-2.svg){#fig-question-mark-linlog-2}\n:::\n\nQuestion mark function including right subtree\n:::\n\n\nHere are graphs describing *our* question mark function, on linear and logarithmic plots.\nInstead of repeating, the function continues its self-similar behavior\n as it proceeds onward to infinity (logarithmically).\nThe right graph stretches from -∞, where its value would be 0, to ∞, where its value would be 2.\n\nPersonally, I like this definition a bit better, if only because it matches other ways\n of thinking about the interval (0, 1).\nFor example,\n\n- In topology, it's common to show that this interval is homeomorphic to the entire real line\n- It's similar to the [rational functions which appear in stereography](/posts/math/stereo/1/),\n which continue to infinity instead of being periodic\n- It showcases how the Stern-Brocot tree sorts rational numbers by complexity better\n\nHowever, it's also true that different definitions are good for different things.\nFor example, periodicity matches the intuition that numbers can be decomposed\n into a fractional and integral part.\nIntegral parts grow without bound, while fractional parts are periodic,\n just like the function would be.\n\n\nClosing\n-------\n\nI'd like to draw this discussion of enumerating numbers to a close for now.\nI wrote this article to establish some preliminaries regarding *another* post that I have planned.\nOn the other hand, since I was describing the Stern-Brocot tree, I felt it also pertinent\n to show the question mark function, since it's a very interesting self-similar curve.\nEven then, I have shown them as a curiosity instead of giving them their time in the spotlight.\n\nI have omitted some things I would like to have discussed, such as\n [order type](https://en.wikipedia.org/wiki/Order_type),\n and enumerating things beyond just the quadratic irrationals.\nI may return to some of these topics in the future, such as to show a way to order integer polynomials.\n\nDiagrams created with GeoGebra (because trying to render them in LaTeX would have taken too long)\n and Matplotlib.\n\n",
"supporting": [
"index_files/figure-html"
],
"filters": [],
"includes": {
"include-in-header": [
"<script src=\"https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js\" integrity=\"sha512-c3Nl8+7g4LMSTdrm621y7kf9v3SDPnhxLNhcjFJbKECVnmZHTdo+IRO05sNLTH/D3vA6u1X32ehoLC7WFVdheg==\" crossorigin=\"anonymous\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js\" integrity=\"sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==\" crossorigin=\"anonymous\" data-relocate-top=\"true\"></script>\n<script type=\"application/javascript\">define('jquery', [],function() {return window.jQuery;})</script>\n"
]
}
}
}