Search code examples
pythonfractions

The number 0.6 is not converting to a fraction correctly


I am trying to create a program that factors quadratics. I was mostly successful, but I am having trouble with the quadratic 5x^2 -13x + 6 in which one of the roots is 0.6, or 3/5. I want to write it as a fraction, but it is not working correctly. It is giving me the following:

5(x - 2)(x - 5404319552844595/9007199254740992)

This is the code I used after importing from fractions:

    s1 = Fraction(((-b + sqrt(disc))/(2*a)))
    s2 = Fraction(((-b - sqrt(disc))/(2*a)))

Anyone know why this may not be working correctly? Or an easier way to factor the quadratics would be useful too.


Solution

  • Quoting the Python manual:

    Note that due to the usual issues with binary floating-point (see Floating Point Arithmetic: Issues and Limitations), the argument to Fraction(1.1) is not exactly equal to 11/10, and so Fraction(1.1) does not return Fraction(11, 10) as one might expect.

    The suggested treatment for a case when you know the numerator and denominator must be small is to limit the denominator. Here is an example:

    from math import sqrt
    from fractions import Fraction
    a, b, c = 5, -13, 6
    disc = b * b - 4 * a * c
    s1 = Fraction(((-b + sqrt(disc))/(2*a)))
    s2 = Fraction(((-b - sqrt(disc))/(2*a)))
    print (s1, s2)
    s1, s2 = s1.limit_denominator (), s2.limit_denominator ()
    print (s1, s2)
    

    The first one prints the fraction you mentioned, the second one gives 3/5.