4

I was reading the documentation of Python3.4 and came across a method 'as_integer_ratio' (This method is defined for python2.7 also).

The documentation says, 'Return a pair of integers whose ratio is exactly equal to the original float and with a positive denominator. Raises OverflowError on infinities and a ValueError on NaNs."

I tried for 56.9, and the output was:

>>> b = 56.9
>>> b.as_integer_ratio()
(8007963087418163, 140737488355328)
>>>

Out of curiosity, any idea regarding how these values are getting calculated? The values could also have been (569, 10), right? Or am I missing something trivial?

akash12300
  • 412
  • 2
  • 12
  • 2
    I would expect it's at least partially because [56.9 isn't exactly 56.9](http://www.cs.wisc.edu/~rkennedy/exact-float?number=56.9). – Rob Kennedy Mar 21 '16 at 19:45
  • 2
    To get (569, 10), use the [`fractions`](https://docs.python.org/3/library/fractions.html#fractions.Fraction.limit_denominator) module. `__import__('fractions').Fraction(56.9).limit_denominator()` – Bhargav Rao Mar 21 '16 at 19:47
  • That's a new info, thanks. But I am still curious as in how 'as_integer_ratio' is calculating those massive integers for something as small as 56.9. – akash12300 Mar 21 '16 at 19:51
  • 1
    Np, The question is great. I remember that I had learned that `fractions` module from a Stack Overflow answer a few years back, so I could find that out. :-) – Bhargav Rao Mar 21 '16 at 20:02

0 Answers0