Question

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.

Was it helpful?

Solution 2

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.

OTHER TIPS

>>> from fractions import Fraction
>>> Fraction(0.6)
Fraction(5404319552844595, 9007199254740992)
>>> Fraction("0.6")
Fraction(3, 5)

0.6 can't be represented exactly as a binary float. See Floating Point Arithmetic: Issues and Limitations. This is not a Python issue, it's an issue with how floating point numbers work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top