I needed to convert floating point numbers to int/int fractions. Python technically has this functionality, but has issues with rounding errors:
>>> (0.1+0.2).as_integer_ratio() (1351079888211149, 4503599627370496)
This is what I wrote and I was wondering whether it could be further improved for performance?
def as_fraction(number: float, accuracy: float) -> (int, int): whole, x = divmod(number, 1) if not x: return int(whole), 1 n = 1 while True: d = int(n/x) if n/d-x < accuracy: return int(whole)*d+n, d d += 1 if x-n/d < accuracy: return int(whole)*d+n, d n += 1