Search code examples
pythonpython-3.xfractions

Get the most simplified fraction


I'm writing a program that uses the Fractions module. I want to get the most simplified fraction of a float. When I try it with numbers like 0.5, it works correctly:

>>> import fractions
>>> str(fractions.Fraction(0.5))
'1/2'

But when I try it with 0.55 or 0.1 it displays fractions with very high numerator and denominator, instead of 11/20 and 1/10.

>>> str(fractions.Fraction(0.1))
'3602879701896397/36028797018963968'
>>> str(fractions.Fraction(0.55))
'2476979795053773/4503599627370496'

What can I do to be sure that the script will always display the most simplified fraction? Is there any way to do it with Fractions module or another module, or I have to write the function myself?


Solution

  • When you pass 0.55 you are passing in a float, so it is already an inexact representation before the Fraction receives the value.

    Alternatively, if you pass a string instead, you can get the exact value you want:

    >>> fractions.Fraction('0.55')
    Fraction(11, 20)