asgarth
asgarth

Reputation: 77

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.

Upvotes: 4

Views: 585

Answers (2)

user2357112
user2357112

Reputation: 282198

If you want to work with fractions, you need to perform all the operations in exact math, not just convert to Fraction at the end. That means no dividing ints by ints - that'll give you a float.

from fractions import Fraction as F

1 + F(1, 2 + F(1, 2))
# or, taking advantage of how int/Fraction gives a Fraction,
1 + 1/(2 + F(1, 2))

Otherwise, you'll lose precision to floating-point rounding, and you'll be stuck with options like using limit_denominator to guess what the unrounded result might have been.

Upvotes: 5

Brendan Abel
Brendan Abel

Reputation: 37599

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.

Upvotes: 6

Related Questions