[Python-Dev] float.decode()?

Tim Peters tim.one@comcast.net
Mon, 15 Apr 2002 18:14:28 -0400


[Neil Schemenauer]
> Common Lisp has a function called decode-float:
>
>     (decode-float float) => significand, exponent, sign
>
>     computes three values that characterize float. The first value is of
>     the same type as float and represents the significand. The second
>     value represents the exponent to which the radix (notated in this
>     description by b) must be raised to obtain the value that, when
>     multiplied with the first result, produces the absolute value of
>     float. If float is zero, any integer value may be returned, provided
>     that the identity shown for scale-float holds. The third value is of
>     the same type as float and is 1.0 if float is greater than or equal
>     to zero or -1.0 otherwise.
>
> How hard would it be to write a method like this for Python floats?  I
> think it could go a long way in helping people understand how floating
> point works.

Python's math.frexp() already exposes a very similar standard C function.
If you take the terms as defined above, it's

    math.frexp(float) => significand * sign, exponent

>>> math.frexp(18)
(0.5625, 5)
>>> math.frexp(-18.5)
(-0.578125, 5)
>>>

Separating out the sign is a nice little convenience, reflecting common use
(most uses of frexp() immediately test-and-branch on the significand's sign
bit right after!).

"decode-float" sounds like some Unicode function, while "frexp" is
wonderfully mnemonic <wink>.