|
1 | | -Given fractions *x* and *y*, say that *x* is **simpler** than *y* if, when both |
2 | | -*x* and *y* are written in lowest terms: |
| 1 | +The **simplefractions** package finds the simplest fraction that converts |
| 2 | +to a given float, or more generally, the simplest fraction that lies within |
| 3 | +a given interval. |
3 | 4 |
|
4 | | -- the numerator of *x* is no larger in absolute value than the numerator of |
5 | | - *y*, and |
6 | | -- the denominator of *x* is no larger than the denominator of *y*, and |
7 | | -- *x* and *y* are not equal to each other in absolute value |
| 5 | +**Definition.** Given fractions *x = a/b* and *y = c/d* (written in lowest |
| 6 | +terms with positive denominators), say that *x* is **simpler** than *y* if |
| 7 | +*abs(a) <= abs(c)*, *b <= d*, and at least one of these two inequalities |
| 8 | +is strict. |
| 9 | + |
| 10 | +For example, 22/7 is simpler than 23/8, but neither of 3/8 and 4/7 is |
| 11 | +simpler than the other. |
| 12 | + |
| 13 | +Then it's a theorem that given any subinterval *I* of the real line that |
| 14 | +contains at least one fraction, that interval contains a unique simplest |
| 15 | +fraction. That is, there's a fraction *a/b* in *I* such that *a/b* is |
| 16 | +simpler (in the above sense) than all other fractions in *I*. As a |
| 17 | +consequence, for any given finite Python float *x*, there's a unique |
| 18 | +simplest fraction that rounds to that float. |
8 | 19 |
|
9 | 20 | The **simplefractions** package provides two functions: |
10 | 21 |
|
@@ -92,6 +103,15 @@ last place) in either direction. `simplest_from_float` can't do that, but |
92 | 103 | Fraction(33, 10) |
93 | 104 | ``` |
94 | 105 |
|
| 106 | +Alternatively, you might ask for the simplest fraction approximating `x` |
| 107 | +with a relative error of at most 0.000001: |
| 108 | + |
| 109 | +```python |
| 110 | +>>> relerr = 1e-6 |
| 111 | +>>> simplest_in_interval(x - relerr*x, x + relerr*x) |
| 112 | +Fraction(33, 10) |
| 113 | +``` |
| 114 | + |
95 | 115 | Here are some more examples of `simplest_in_interval` at work. The inputs |
96 | 116 | to `simplest_in_interval` can be floats, integers, or `Fraction` objects. |
97 | 117 |
|
|
0 commit comments