Search code examples
pythonfractions

Fraction function from fractions module python problem


>>> n=F.Fraction(3.56)
>>> n
Fraction(8016407336719483, 2251799813685248)
>>> n=F.Fraction('3.56')
>>> n
Fraction(89, 25)

Is it working as intended? Both results are correct, but the first one seems to be over the top. I stubmled it upon while solving this kata from codewars.


Solution

  • Because of the usual issues with binary floating-point, the Fraction(floating) doesn't return the expected fraction object, different from the decimal or string, that is treated like a exact number.

    But you can treat this issue using a method called "limit_denominator" that have a default argument "max_denominator=1000000",so, you only need to call:

    Fraction(3.16).limit_denominator()
    

    Take a look at the docs: https://docs.python.org/3/library/fractions.html#fractions.Fraction.limit_denominator