[Python-Dev] Float --> Integer Ratio

Jeffrey Yasskin jyasskin at gmail.com
Fri Jan 25 01:09:53 CET 2008


+1. Where do people want it, and what should its name be? I can
implement it if you like.

Another plausible output would be similar to frexp but with an integer
for the mantissa instead of a float. So:
 A) math.frexp(3.2) == (0.80000000000000004, 2)
 B) integral_frexp(3.2) == (3602879701896397, -50)
 C) exact_integral_ratio(3.2) == (3602879701896397, 1125899906842624)

(B) is easier to implement in C (not that that's a deciding factor);
(C) is probably more useful. So I'd vote for (C), your suggestion, but
just wanted to make the choice explicit.

Also, to make things explicit, the implementation in rational.py
doesn't guarantee that the fraction is in lowest terms. Should the
library version?

On Jan 24, 2008 3:10 PM, Raymond Hettinger <python at rcn.com> wrote:
> 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)
>     """
> _______________________________________________
> Python-Dev mailing list
> Python-Dev at python.org
> http://mail.python.org/mailman/listinfo/python-dev
> Unsubscribe: http://mail.python.org/mailman/options/python-dev/jyasskin%40gmail.com
>



-- 
Namasté,
Jeffrey Yasskin
http://jeffrey.yasskin.info/

"Religion is an improper response to the Divine." — "Skinny Legs and
All", by Tom Robbins


More information about the Python-Dev mailing list