Implementation limitations of float.as_integer_ratio()
Question: Recently, a correspondent mentioned
[`float.as_integer_ratio()`](http://docs.python.org/library/stdtypes.html#numeric-
types-int-float-long-complex), new in Python 2.6, noting that typical floating
point implementations are essentially rational approximations of real numbers.
Intrigued, I had to try π:

    
    
    >>> float.as_integer_ratio(math.pi);
    (884279719003555L, 281474976710656L)
    

I was mildly surprised not to see the more
[accurate](http://en.wikipedia.org/wiki/Pi) result due to
[Arima](http://en.wikipedia.org/wiki/Arima_Yoriyuki),:

    
    
    (428224593349304L, 136308121570117L)
    

For example, this code:

    
    
    #! /usr/bin/env python
    from decimal import *
    getcontext().prec = 36
    print "python: ",Decimal(884279719003555) / Decimal(281474976710656)
    print "Arima:  ",Decimal(428224593349304) / Decimal(136308121570117)
    print "Wiki:    3.14159265358979323846264338327950288"
    

produces this output:

    
    
    python:  3.14159265358979311599796346854418516
    Arima:   3.14159265358979323846264338327569743
    Wiki:    3.14159265358979323846264338327950288
    

Certainly, the result is correct given the precision afforded by 64-bit
floating-point numbers, but it leads me to ask: How can I find out more about
the implementation limitations of `as_integer_ratio()`? Thanks for any
guidance.

Additional links: [Stern-Brocot](http://en.wikipedia.org/wiki/Stern-
Brocot_tree), [Python
source](http://svn.python.org/view/python/trunk/Objects/floatobject.c?revision=77139&view=markup),
[IronPython
source](http://www.google.com/codesearch/p?hl=en#4BXx6j5BqI4/IronPython_Main/Src/IronPython/Runtime/Operations/FloatOps.cs&q=as_integer_ratio&sa=N&cd=2&ct=rc).


Answer: The algorithm used by `as_integer_ratio` only [considers powers of 2 in the
denominator](http://www.google.com/codesearch/p?hl=en#4BXx6j5BqI4/IronPython_Main/Src/IronPython/Runtime/Operations/FloatOps.cs&q=as_integer_ratio&sa=N&cd=2&ct=rc).
Here is a (probably) [better algorithm](http://www.math.niu.edu/~rusin/known-
math/95/rationalize).

