pythonfractionspython-fractions

Python automatically converts the numerator and denominator of some fractions into big numbers. Why?


Here is an example:

x = frac(1,3)
x
Out[138]: Fraction(1, 3)
y = frac(5/39)
y
Out[140]: Fraction(288692283805801, 2251799813685248)
print(x+y)
3117876665102651/6755399441055744
x+y
Out[142]: Fraction(3117876665102651, 6755399441055744)

Why is 5/39 automatically converted to 288692283805801/2251799813685248? Using Python 3.7.8


Solution

  • 5/39 is a floating point number, that's not representable as 5/39 exactly. The fraction with large numerator and denominator is the rational that exactly represents the floating point number that approximates 5/39.

    Try fractions.Fraction(5, 39) instead.

    A similar example is given in the docs for the fractions module, with Fraction(1.1) not returning Fraction(11, 10) as one might naively expect. https://docs.python.org/3/library/fractions.html