|
| 1 | +fractions |
| 2 | +========= |
| 3 | + |
| 4 | +This document describes the working and implementation details of the |
| 5 | +[`fractions`](https://docs.python.org/3/library/fractions.html) module, |
| 6 | +providing some proofs for algorithms used. |
| 7 | + |
| 8 | + |
| 9 | +# Proof of correctness of the `limit_denominator` algorithm |
| 10 | + |
| 11 | +## The problem being solved |
| 12 | + |
| 13 | +The `limit_denominator` algorithm takes a fraction $m/n$ and a positive integer |
| 14 | +$\ell$, and aims to return a "best" approximation to $m/n$ from amongst all |
| 15 | +fractions $r/s$ with denominator bounded by $\ell$. To make "best" precise, |
| 16 | +let's establish some conventions and terminology: |
| 17 | + |
| 18 | +- All fractions are assumed to be in lowest terms, with positive denominator. |
| 19 | +- A **candidate approximation** to $m / n$ with denominator bounded by $\ell$ |
| 20 | + (or just **candidate** for short) is a fraction $r/s$ with $s \le \ell$. |
| 21 | +- Given two candidates $r/s$ and $t/u$, say that $r/s$ is **better** than $t/u$ |
| 22 | + if _either_ |
| 23 | + - $r/s$ is closer to $m/n$ than $t/u$ is, _or_ |
| 24 | + - $r/s$ and $t/u$ are equidistant from $m/n$, and $s \le u$. |
| 25 | +- A candidate $r/s$ is a **best approximation** if it's better than all (other) |
| 26 | + candidates. |
| 27 | + |
| 28 | +The goal of this exposition is to convince the reader that Python's |
| 29 | +implementation of `limit_denominator` always returns a best approximation for |
| 30 | +the given inputs. |
| 31 | + |
| 32 | +Some notes: |
| 33 | + |
| 34 | +- There's a tension with the English language: our "better" relation is |
| 35 | + reflexive (a candidate $r/s$ is better than itself), while the word "better" |
| 36 | + suggests an irreflexive relation. But other more accurate wordings ("no worse |
| 37 | + than", "better or equally good", "at least as good") are more cumbersome, so |
| 38 | + we'll live with the tension. |
| 39 | +- We'll show below that outside one corner case, there's a _unique_ best |
| 40 | + approximation for a given set of arguments. That corner case is the case |
| 41 | + where $m/n$ is exactly halfway between two consecutive integers and $\ell = 1$; |
| 42 | + we'll call this the ambiguous case, and we'll return to it below. |
| 43 | +- For an example of the tie-break condition for "better", consider the case |
| 44 | + where $m/n = 99/140 = 0.707142...$ and $\ell = 10$. Then $7/10 = 0.7$ and |
| 45 | + $5/7 = 0.714285...$ are candidate approximations, they're equidistant from the |
| 46 | + target fraction $99/140$, and they're each closer than any other candidate - |
| 47 | + any fraction that's closer must be strictly between $7/10$ and $5/7$, and all |
| 48 | + fractions in the open interval $(7/10, 5/7)$ have denominator larger than $10$. |
| 49 | + Since $5/7$ has smaller denominator than $7/10$, our definition says that $5/7$ |
| 50 | + is better than $7/10$ (but not vice versa). So $5/7$ is the unique best |
| 51 | + approximation. |
| 52 | + |
| 53 | +## Simplifying the code |
| 54 | + |
| 55 | +Here's the standard library implementation of `Fraction.limit_denominator`, shorn of |
| 56 | +comments and docstring details, but otherwise unaltered. |
| 57 | + |
| 58 | +```python |
| 59 | +class Fraction(numbers.Rational): |
| 60 | + |
| 61 | + # other methods elided ... |
| 62 | + |
| 63 | + def limit_denominator(self, max_denominator=1000000): |
| 64 | + """Closest Fraction to self with denominator at most max_denominator.""" |
| 65 | + if max_denominator < 1: |
| 66 | + raise ValueError("max_denominator should be at least 1") |
| 67 | + if self._denominator <= max_denominator: |
| 68 | + return Fraction(self) |
| 69 | + |
| 70 | + p0, q0, p1, q1 = 0, 1, 1, 0 |
| 71 | + n, d = self._numerator, self._denominator |
| 72 | + while True: |
| 73 | + a = n//d |
| 74 | + q2 = q0+a*q1 |
| 75 | + if q2 > max_denominator: |
| 76 | + break |
| 77 | + p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 |
| 78 | + n, d = d, n-a*d |
| 79 | + k = (max_denominator-q0)//q1 |
| 80 | + |
| 81 | + if 2*d*(q0+k*q1) <= self._denominator: |
| 82 | + return Fraction._from_coprime_ints(p1, q1) |
| 83 | + else: |
| 84 | + return Fraction._from_coprime_ints(p0+k*p1, q0+k*q1) |
| 85 | +``` |
| 86 | + |
| 87 | +Instead of proving correctness of the above code directly, we'll prove correctness |
| 88 | +of an equivalent simplified version. Here's that version: |
| 89 | + |
| 90 | +```python |
| 91 | +def limit_denominator(m: int, n: int, l: int) -> tuple[int, int]: |
| 92 | + """ |
| 93 | + Given a fraction m/n and a positive integer l, return integers r and s such |
| 94 | + that r/s is the closest fraction to m/n with denominator bounded by l. |
| 95 | +
|
| 96 | + m/n need not be in lowest terms, but n must be positive. |
| 97 | +
|
| 98 | + On return, 0 < s <= l and gcd(r, s) = 1. |
| 99 | + """ |
| 100 | + if l < 1: |
| 101 | + raise ValueError("max_denominator should be at least 1") |
| 102 | + |
| 103 | + a, b, p, q, r, s, v = n, m % n, 1, 0, m // n, 1, 1 |
| 104 | + while 0 < b and q + a // b * s <= l: |
| 105 | + a, b, p, q, r, s, v = b, a % b, r, s, p + a // b * r, q + a // b * s, -v |
| 106 | + k = (l - q) // s |
| 107 | + t, u = p + k * r, q + k * s |
| 108 | + return (r, s) if 2 * b * u <= n else (t, u) |
| 109 | +``` |
| 110 | + |
| 111 | +The differences with the standard library version are mostly cosmetic: there |
| 112 | +are some de-optimizations (like computing `a//b` several times); we deal purely |
| 113 | +with integers to avoid the `Fraction` unpacking and repacking; some variables |
| 114 | +are renamed, and we've removed the fast path where a `Fraction` is returned |
| 115 | +unaltered if its denominator is _already_ at most `l`. The most significant |
| 116 | +difference is that we've unrolled the first loop-and-a-half of the `while` |
| 117 | +loop, with the side-effect of shifting the `break` condition to the top of the |
| 118 | +loop, where it becomes the loop guard. There's also an extra variable `v`, |
| 119 | +which alternates between values `1` and `-1`. It's not needed for computing the |
| 120 | +final result, but we'll be making use of it in the statements and proofs below. |
| 121 | +Finally, the standard library code has no positivity check in the `break` |
| 122 | +condition to match the `0 < b` check in the loop guard - that check proves to |
| 123 | +be unnecessary if the fast path is present. |
| 124 | + |
| 125 | +## Proof overview |
| 126 | + |
| 127 | +The main loop of `limit_denominator` is a variant of the extended Euclidean |
| 128 | +algorithm applied to $m$ and $n$, with an extra termination condition designed |
| 129 | +to make sure that denominators don't go out of bounds - the moment a full |
| 130 | +Euclidean step would give us a denominator larger than $\ell$, we halt the |
| 131 | +loop. After the loop we take a partial Euclidean step, advancing exactly as far |
| 132 | +as possible without violating the denominator bound. |
| 133 | + |
| 134 | +The main loop, together with that partial Euclidean step, produces candidate |
| 135 | +approximations $r/s$ and $t/u$ which bracket the target fraction $m/n$, and |
| 136 | +whose denominators are no greater than the limit $\ell$. With just two |
| 137 | +additional pieces of information, namely that $ts - ru = ±1$ and that |
| 138 | +$\ell < s + u$, we can deduce that _all_ fractions strictly between $r/s$ and |
| 139 | +$t/u$ have denominator greater than $\ell$, hence that either $r/s$ or $t/u$ |
| 140 | +is a best approximation. The final line of the code then determines which of |
| 141 | +these two fractions is better and returns it. |
| 142 | + |
| 143 | +In more detail, we'll show in the sections below that after exiting the `while` |
| 144 | +loop and defining $t$ and $u$, the following five properties hold: |
| 145 | + |
| 146 | +- $(ts - ru)v = 1$ |
| 147 | +- $0 < s \le \ell$ |
| 148 | +- $0 < u \le \ell$ |
| 149 | +- $\ell < s + u$ |
| 150 | +- $r/s \le m/n < t/u$ if $v=1$, and $t/u < m/n \le r/s$ if $v = -1$ |
| 151 | + |
| 152 | +Note that the first three properties make $r/s$ and $t/u$ well-defined as |
| 153 | +fractions, and moreover both are candidates: reduced, with a positive |
| 154 | +denominator bounded by $\ell$. We now show that the five properties imply that |
| 155 | +any fraction $y/z$ strictly between $r/s$ and $t/u$ has $z > \ell$. We have: |
| 156 | + |
| 157 | +$$z = (ts - ru)vz = (tz - yu)vs + (ys - rz)vu.$$ |
| 158 | + |
| 159 | +Now $v$ is either $1$ or $-1$. If $v = 1$ then $r/s < t/u$, so $r/s < y/z < t/u$. |
| 160 | +So $ys - rz$ and $tz - yu$ are positive, hence $(ys - rz)v$ and $(tz - yu)v$ |
| 161 | +are positive integers. Conversely if $v = -1$ then $t/u < r/s$, so |
| 162 | +$t/u < y/z < r/s$ and $ys - rz$ and $tz - yu$ are negative. So again |
| 163 | +$(ys - rz)v$ and $(tz - yu)v$ are positive integers. So in either case, |
| 164 | +$(tz - yu)v \ge 1$ and $(ys - rz)v \ge 1$, hence |
| 165 | +$$z = [(tz-yu)v]s + [(ys - rz)v]u \ge s + u > \ell.$$ |
| 166 | + |
| 167 | +At this point $r/s$ and $t/u$ are candidates, there are no candidates strictly |
| 168 | +between $r/s$ and $t/u$, while $m/n$ _does_ lie between $r/s$ and $t/u$ (and |
| 169 | +may be equal to $r/s$, but not to $t/u$). It follows that $r/s$ and $t/u$ are |
| 170 | +the only possible best approximations to $m/n$, and that either $r/s$ or $t/u$ |
| 171 | +(or possibly both) is a best approximation. The code need only determine which |
| 172 | +of $r/s$ and $t/u$ is better than the other. The details are given in the |
| 173 | +"Choosing the best approximation" section below, while the proofs of the five |
| 174 | +properties that we used above are in the "Details" sections below. |
| 175 | + |
| 176 | +## Details: loop invariants |
| 177 | + |
| 178 | +Both the initial state and the state after every iteration of the `while` loop |
| 179 | +satisfy the following six invariants: |
| 180 | + |
| 181 | +- $(ps - rq)v = 1$ |
| 182 | +- $(pn - mq)v = a$ |
| 183 | +- $(ms - rn)v = b$ |
| 184 | +- $0 \le b < a$ |
| 185 | +- $0 \le q$ |
| 186 | +- $0 < s \le \ell$ |
| 187 | + |
| 188 | +These are all easily proved by induction: they hold for the initial state by |
| 189 | +inspection, and it's easy to see that the way that the variables are updated |
| 190 | +within the `while` loop keeps all of these properties invariant. Note that at |
| 191 | +the end of an iteration of the `while` loop, the condition $s \le \ell$ is |
| 192 | +exactly the condition that the loop was entered (that |
| 193 | +$q + \lfloor a / b \rfloor s \le \ell$). |
| 194 | + |
| 195 | +That $v$ is either $1$ or $-1$ follows from the first invariant. |
| 196 | + |
| 197 | +## Details: loop termination |
| 198 | + |
| 199 | +For a complete proof of correctness we need to establish that our `while` loop |
| 200 | +does not run indefinitely - it must terminate after a finite number of |
| 201 | +iterations. But this follows immediately from the observation that the value of |
| 202 | +$a$ remains positive and that it strictly decreases at every iteration: at each |
| 203 | +iteration the new value of $a$ is the old value of $b$, which from our loop |
| 204 | +invariant $b < a$ is smaller than the old value of $a$. |
| 205 | + |
| 206 | +## Details: after the loop |
| 207 | + |
| 208 | +Here we prove that the five properties mentioned earlier hold. |
| 209 | + |
| 210 | +One of our two possible return values, $r/s$, comes directly from the loop. We |
| 211 | +construct the second candidate $t/u$ after the loop: $t = p + kr$ and |
| 212 | +$u = q + ks$, with $k = \lfloor (\ell - q) / s \rfloor$. Think of $t/u$ as |
| 213 | +the result of taking a _partial_ Euclidean step, as a replacement for the |
| 214 | +full Euclidean step which would have taken the denominator out of bounds. |
| 215 | + |
| 216 | +That $0 < s \le \ell$ follows directly from the loop invariants. From the |
| 217 | +definition of $k$ we have $ks \le \ell - q < s + ks$, hence |
| 218 | +$ks + q \le \ell < s + ks + q$, that is |
| 219 | +$$u \le \ell < s + u.$$ |
| 220 | +That $u$ is positive follows from $s \le \ell < s + u$. So $t/u$ is also a |
| 221 | +valid candidate approximation. |
| 222 | + |
| 223 | +From construction of $t$ and $u$ and the relation $(ps - rq)v = 1$ we get an |
| 224 | +analogous relation for $r/s$ and $t/u$: |
| 225 | +$$(ts - ru)v = 1.$$ |
| 226 | + |
| 227 | +We also define an integer $c = a - kb$, the result of taking the partial |
| 228 | +Euclidean step that gives $t$ and $u$. It's immediate from the definitions |
| 229 | +and the earlier loop invariants that: |
| 230 | +$$(tn - mu)v = c$$ |
| 231 | +and |
| 232 | +$$bt + cr = m$$ |
| 233 | +and finally, |
| 234 | +$$bu + cs = n.$$ |
| 235 | + |
| 236 | +We next prove that $b \le c$. The intuition here is that a full Euclidean step |
| 237 | +would have given us the nonnegative remainder $a \bmod b$; since we took only a |
| 238 | +partial step instead, our remainder $c = a - kb$ is the full remainder |
| 239 | +$a \bmod b$ plus at least one copy of $b$. Concretely, there are two cases. |
| 240 | +If $0 < b$ then from the failed loop guard $\ell < q + \lfloor a /b \rfloor s$. |
| 241 | +But $q + ks = u \le \ell$, so $k < \lfloor a/b \rfloor$, from which |
| 242 | +$c = a - kb \ge a - b\lfloor a/b \rfloor + b \ge b$. Otherwise $b = 0$ |
| 243 | +and $c = a - kb = a$, and the result is immediate from the positivity of $a$. |
| 244 | + |
| 245 | +Finally, note that $0 < c$. If $0 < b$ this follows from $b \le c$. If $b = 0$ |
| 246 | +it follows from the positivity of $a$ together with $c = a - kb = a$. |
| 247 | + |
| 248 | +We've now established four of the five properties that were used in the proof |
| 249 | +overview above. The only property that we're missing is that $m/n$ lies between |
| 250 | +$r/s$ and $t/u$ (and can be equal to $r/s$, but not to $t/u$). But this follows |
| 251 | +from the facts that $0 \le b = (ms - rn)v$ and that $0 < c = (tn - mu)v$: |
| 252 | +if $v = 1$ then these give $r/s \le m/n < t/u$, while if $v = -1$ then |
| 253 | +$t/u < m/n \le r/s$. |
| 254 | + |
| 255 | +## Choosing the best approximation |
| 256 | + |
| 257 | +By the time we get to the final line of `limit_denominator`, we know that |
| 258 | +either $r/s$ or $t/u$ is our best approximation; we need to choose the one |
| 259 | +that's closer to $m/n$. So we want to compare $|m/n - r/s|$ with $|t/u - m/n|$. |
| 260 | +Scaling up by $nsu$, we need to compare $|(ms - rn)u|$ with $|(tn - mu)s|$. |
| 261 | +Since $v$ is either plus or minus one, we can insert a factor of $v$ without |
| 262 | +affecting the absolute value, so we're now comparing $|(ms-rn)vu|$ with |
| 263 | +$|(tn - mu)vs|$. But from above, $(ms-rn)v = b$ is nonnegative, as is |
| 264 | +$(tn - mu)v = c$. So the comparison we want to make is |
| 265 | +$$bu \le cs.$$ |
| 266 | +Adding $bu$ to both sides and using the fact that $bu + cs = n$, this is |
| 267 | +equivalent to the check |
| 268 | +$$2bu \le n,$$ |
| 269 | +which is the check that we use in the code. |
| 270 | + |
| 271 | +In the case that $r/s$ and $t/u$ are equidistant from $m/n$, we have $bu = cs$ |
| 272 | +(or equivalently $2bu = n$), and $r/s$ is returned. Since $b \le c$ and $c$ is |
| 273 | +positive, we must have $s = (b/c) u \le u$, so in this case $r/s$ is better |
| 274 | +than $t/u$ by the tie-break condition, so $r/s$ is a best approximation. |
| 275 | + |
| 276 | +## Uniqueness, and the ambiguous case |
| 277 | + |
| 278 | +From earlier, any best approximation must be either $r/s$ or $t/u$, and at |
| 279 | +least one of these _is_ a best approximation. Outside one corner case _exactly_ |
| 280 | +one of these is a best approximation, so there's a unique best approximation to |
| 281 | +$m/n$ with denominator bounded by $\ell$, and `limit_denominator` returns that |
| 282 | +best approximation. In this section we explore the corner case where _both_ |
| 283 | +$r/s$ and $t/u$ are best approximations, and we describe what |
| 284 | +`limit_denominator` returns in that situation. |
| 285 | + |
| 286 | +So suppose that both $r/s$ and $t/u$ are best approximations. Then each is |
| 287 | +better than the other, so from the definition of _better_ (including the |
| 288 | +tie-break condition) they must be equidistant from $m/n$, and we must also have |
| 289 | +$s \le u$ and $u \le s$, hence $s = u$. From $(ts - ru)v = 1$ and $s = u$ we |
| 290 | +have $s = u = 1$, so $t = r \pm 1$ and the candidates $r/s$ and $t/u$ are |
| 291 | +consecutive integers (in some order). Since $m/n$ is equidistant from both, |
| 292 | +it's a half-integer - a value of the form $w + 1/2$ for some integer $w$. |
| 293 | +Moreover, since $\ell < s + u$ and $\ell$ is positive, we must have $\ell = 1$. |
| 294 | + |
| 295 | +Conversely, if $m / n$ is a half-integer and $\ell = 1$ then our candidates |
| 296 | +(denominator bounded by $1$) are simply integers, so it's clear that there are |
| 297 | +exactly _two_ best approximations to $m / n$, namely the floor and ceiling of |
| 298 | +$m / n$. |
| 299 | + |
| 300 | +We call the case where $m / n$ is a half-integer and $\ell = 1$ the |
| 301 | +**ambiguous** case. The above argument shows that uniqueness fails precisely in |
| 302 | +the ambiguous case: if $\ell > 1$ or $m / n$ is _not_ a half-integer, then |
| 303 | +there's a _unique_ best approximation to $m / n$ with denominator bounded by |
| 304 | +$\ell$. |
| 305 | + |
| 306 | +We now prove that in the ambiguous case, the `limit_denominator` algorithm |
| 307 | +returns the floor of $m / n$ rather than the ceiling. So suppose again that |
| 308 | +both $r/s$ and $t/u$ are best approximations. They are then equidistant from |
| 309 | +$m/n$, so as shown in the previous section $2bu = n$ and `limit_denominator` |
| 310 | +returns $r/s$. We need to show that $r/s$ is the lower of the two candidates; |
| 311 | +that is, that $r/s < t/u$, or equivalently that $v = 1$. |
| 312 | + |
| 313 | +We first claim that $q = 0$. From the loop invariants it follows that |
| 314 | +$$as + bq = (pn - mq)vs + (ms - rn)vq = (ps - rq)vn = n$$ |
| 315 | +so we have |
| 316 | +$$as + bq = 2bu.$$ |
| 317 | +Subtracting $bs$ from both sides and rearranging gives |
| 318 | +$$(a - b)s = b(2u - q - s).$$ |
| 319 | +But $b < a$ and $0 < s$ from the loop invariants, so the left-hand side is |
| 320 | +positive. Since $b$ is nonnegative, $2u - q - s$ must also be positive. As |
| 321 | +before, we also know that in this ambiguous case $s = u = 1$. So |
| 322 | +$2u - q - s = 1 - q$ and $1 - q$ is positive, so since $q$ is nonnegative, |
| 323 | +$q = 0$ is the only possibility. Looking back at the loop, $q$ is nonzero after |
| 324 | +every iteration of the loop body: the only time it's zero is when the loop hasn't |
| 325 | +run. And in that initial loop state we do indeed have $v = 1$, which is what we |
| 326 | +needed. |
| 327 | + |
| 328 | +## Optimizations: removing the $0 < b$ check and avoiding unnecessary `gcd`s |
| 329 | + |
| 330 | +The standard library version of the code has a fast path: if the denominator of |
| 331 | +the target fraction is _already_ bounded by $\ell$, the code simply returns (a |
| 332 | +copy of) the target fraction immediately - a moment's thought should convince |
| 333 | +the reader that $m/n$ is the unique best approximation in this situation. |
| 334 | + |
| 335 | +With the fast path in place, we can simplify the loop guard. Suppose that when |
| 336 | +the loop guard is evaluated, the $0 < b$ part of the condition is false. We |
| 337 | +claim that in that case, $n$ is at most $\ell$. For if $0 < b$ is false, then |
| 338 | +$b = 0$ (we know that $b$ is always nonnegative), the loop exits immediately, |
| 339 | +we construct $t/u$ as before, and the post-loop equations $bt + cr = m$ and |
| 340 | +$bu + cs = n$ give $cr = m$ and $cs = n$. So $c$ is a common factor of $m$ |
| 341 | +and $n$. But since $m$ and $n$ are relatively prime and $c$ is positive, |
| 342 | +$c = 1$, $m = r$ and $n = s$. But $s \le \ell$, so $n \le \ell$. |
| 343 | + |
| 344 | +So if we've _already_ excluded the case that $n \le \ell$ via the fast path, |
| 345 | +then the $0 < b$ condition at the top of the loop is always true, and we can |
| 346 | +drop it. The standard library version of the code does exactly that. |
| 347 | + |
| 348 | +It's worth noting that the simplified listing _does_ require the extra $0 < b$ |
| 349 | +check, for two reasons. First, the simplified listing does not require that its |
| 350 | +inputs $m$ and $n$ be relatively prime (though it does require that $n$ is |
| 351 | +positive). Second, it lacks the fast path. Removing the $0 < b$ check would |
| 352 | +require both adding a fast path _and_ requiring that $m$ and $n$ be relatively |
| 353 | +prime. |
| 354 | + |
| 355 | +One other optimization in the standard library version: since we already know |
| 356 | +that $r/s$ and $t/u$ are in lowest terms, we have no need to construct the |
| 357 | +returned `Fraction` through the default `Fraction` constructor, which would |
| 358 | +require a potentially expensive `gcd` computation. We can use the |
| 359 | +`Fraction._from_coprime_ints` constructor instead. |
| 360 | + |
| 361 | +## Formal proof |
| 362 | + |
| 363 | +In addition to the above proof, a formal, computer-verified proof |
| 364 | +of correctness (using Lean) of the algorithm can be found here: |
| 365 | +https://github.com/mdickinson/snippets/tree/1f47f8cc33185c646b679647e88cb24f29fd6a4e/proofs/limit_denominator |
0 commit comments