Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 693
user3448104 Avatar asked Dec 10 '25 09:12

user3448104


2 Answers

>>> 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.

like image 141
Tim Pietzcker Avatar answered Dec 11 '25 21:12

Tim Pietzcker


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.

like image 26
Gassa Avatar answered Dec 11 '25 22:12

Gassa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!