Find the closest fraction to a decimal with a specific denominator using Python's fractions module
fractions, python
Solution
It's straightforward to calculate the numerator you need without the `fractions` module -- it's just the nearest integer to `16*target_number` -- and if you want a `Fraction` then you can (and should) just say (without stringifying your target number, of course):
Fraction(int(round(16*target_number)),16)
(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.)
Problem
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?