fraction.Fraction.limit_denominator exists, and finds the closest fraction that has a denominator smaller than a given maximum. But there is no obvious way to limit the numerator.
What is the best way to also limit the numerator? (I.e. to find the closest fraction that has both numerator and denominator smaller than a given maximum.)
(Goal: I need to limit the numerator also to 2**32, because TIFF files store fractions as two unsigned 32-bit integers.)
A crude approach (that probably does not find the truly closest fraction):
from fractions import Fraction
def limit_32bit_rational(f: float) -> Fraction:
ndigits = 15
while True:
r = Fraction.from_float(f).limit_denominator(1000000)
if r.numerator < 2**32:
return r
f = round(f, ndigits)
ndigits -= 1
Is there a better way to find the closest fraction that has nominator and denominator less than 2**32?