The Closest Fraction Under a Limit (Rational)
Examples on this page assume from decimo.prelude import * and run inside def main() raises:.
limit_denominator answers the closest fraction whose denominator is at most
the limit, which is how a long exact value becomes a short readable one:
var pi_ish = Rational(BigInt(31415926535), BigInt(10000000000))
print(pi_ish.limit_denominator(BigInt(10))) # 22/7
print(pi_ish.limit_denominator(BigInt(1000))) # 355/113
It walks the continued fraction of the value, so the work is proportional to
the length of that walk and not to the size of the denominator it starts
from. Where two fractions are equally close it returns the same one Python’s
Fraction does, which is not always the one with the smaller denominator.
Built from decimo main. This page in the manual.