Search code examples
pythonpython-3.xfractions

Fraction function returning unreduced fraction


I'm trying to convert a mathematical expression into a reduced fraction. When using the Fraction function from the fractions module I get an unreduced fraction.

The code

from fractions import Fraction

print(Fraction(1 + 1/(2 + 1/2)))

returns 3152519739159347/2251799813685248 which reduces to 7/5.

I would like my code to return the reduced fraction.


Solution

  • This is due to the imprecision of floating point math.

    While it is true that 1 + 1/(2 + 1/2) should reduce to 7/5 (or 1.4), the decimal 1.4 cannot be precisely represented by floating point numbers

    >>> '{:030f}'.format(1.4)
    1.39999999999999999999911182158029987
    

    That inaccuracy is leading it to produce a different fraction than 7/5

    If you want precise fraction math, you need to do the entire equation using fractions and not mix it with floating point numbers.