Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 652
asgarth Avatar asked Dec 17 '22 23:12

asgarth


1 Answers

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.

like image 75
Brendan Abel Avatar answered Jan 06 '23 01:01

Brendan Abel