With Python’s fractions module I can do something like:
>>> from fractions import Fraction
>>> import math
>>> target_number = str( 10 / math.pi )
>>> Fraction( target_number )
Fraction(39788735773, 12500000000)
But what should I do if I want a fraction in sixteenths? That is, Fraction(51, 16). Using limit_denominator(16) only makes the maximum denominator 16:
>>> Fraction( target_number ).limit_denominator(16)
Fraction(35, 11)
Is there a straightforward way to do this with the fractions module?
It’s straightforward to calculate the numerator you need without the
fractionsmodule — it’s just the nearest integer to16*target_number— and if you want aFractionthen you can (and should) just say (without stringifying your target number, of course):(It looks, empirically, as if omitting the
int()doesn’t stop it working, but according to the docs you’re supposed to pass rational numbers in.)