Reputation: 77
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
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 int
s by int
s - 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
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