Batu Lab NotesPractical developer guides

Measure Fraction limit_denominator approximation error exactly

By Batu ยท English technical notes

Measure Fraction limit_denominator approximation error exactly

Use Fraction.limit_denominator(max_denominator) and subtract the approximation from the original Fraction; abs() leaves an exact rational residual. For Fraction(355, 113) with a cap of 10, the approximation is 22/7 and the exact absolute error is 1/791.

Reporting only 22/7 hides the important constraint: it is an approximation chosen under a denominator limit, not the original value. This experiment prints two caps to show that the limit participates in the result. A cap of 5 gives 16/5 with error 33/565, while cap 10 admits 22/7 and greatly reduces the residual. No conversion to float is needed, so neither the approximation nor its difference is rounded for presentation.

The assertions verify these known results for this synthetic rational input. They do not claim that a smaller denominator is suitable for every measurement or downstream format. fractions.Fraction stores rational numbers as normalized numerator/denominator pairs and documents limit_denominator(). That method has been available since Python 3.2.

AI assistance disclosure: this article was drafted with AI assistance and uses a synthetic, locally reproducible fixture.

from fractions import Fraction

target = Fraction(355, 113)

for cap in (5, 10):
    approximation = target.limit_denominator(cap)
    error = abs(target - approximation)

    assert approximation.denominator <= cap
    print(f"cap={cap}: approximation={approximation}, error={error}")

assert target.limit_denominator(10) == Fraction(22, 7)
assert abs(target - Fraction(22, 7)) == Fraction(1, 791)
cap=5: approximation=16/5, error=33/565
cap=10: approximation=22/7, error=1/791