Reputation: 35
>>> n=F.Fraction(3.56)
>>> n
Fraction(8016407336719483, 2251799813685248)
>>> n=F.Fraction('3.56')
>>> n
Fraction(89, 25)
Is it working as intended? Both results are correct, but the first one seems to be over the top. I stubmled it upon while solving this kata from codewars.
Upvotes: 3
Views: 439
Reputation: 56
Because of the usual issues with binary floating-point, the Fraction(floating) doesn't return the expected fraction object, different from the decimal or string, that is treated like a exact number.
But you can treat this issue using a method called "limit_denominator" that have a default argument "max_denominator=1000000",so, you only need to call:
Fraction(3.16).limit_denominator()
Take a look at the docs: https://docs.python.org/3/library/fractions.html#fractions.Fraction.limit_denominator
Upvotes: 3
Reputation: 226
When you wrote 3.56
, it means you declared a number 3.56
as float type. And float type has a small deviation, which cause there's also a small deviation when it converts to fraction type.
But when you wrote '3.56'
, you declared a string. String has a limited length, thus there's no more deviation. When you convert it to string, they will convert it to the exact value.
See also: https://www.daniweb.com/programming/threads/506664/mod-unexpected-result
Upvotes: 1