rational.py contains code for turning a float into an
exact integer ratio. I've needed something like this in
other situations as well. The output is more convenient
than the mantissa/exponent pair returned by math.frexp().
I propose C-coding this function and either putting it in
the math module or making it a method for floats. That
would simplify and speed-up rational.py while making
the tool available for other applications. Also, the
tool is currently in the wrong place (while the output
is clearly useful for rational.py, the internals of
the function are entirely about floats and ints and
has no internal references to the rational module).
Raymond
-------------------------------------------------------
def _binary_float_to_ratio(x):
"""x -> (top, bot), a pair of ints s.t. x = top/bot.
The conversion is done exactly, without rounding.
bot > 0 guaranteed.
Some form of binary fp is assumed.
Pass NaNs or infinities at your own risk.
>>> _binary_float_to_ratio(10.0)
(10, 1)
>>> _binary_float_to_ratio(0.0)
(0, 1)
>>> _binary_float_to_ratio(-.25)
(-1, 4)
"""