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

1
  • 2
    The float 3.56 does not represent exactly one hundredth of 356. If you want exactly one hundredth of 356, you should use '3.56', to avoid floating-point rounding error. (Floating-point rounding error doesn't go away when you pass a float to Fraction.) Commented May 22, 2020 at 2:08

2 Answers 2

3

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

1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.