[Python-Dev] Adding DBL_MANTISSA and such to Python

Michael Hudson mwh at python.net
Thu May 5 10:17:30 CEST 2005


"Edward C. Jones" <edcjones at comcast.net> writes:

> Recently I needed some information about the floating point numbers on 
> my machine. So I wrote a tiny C99 program with the line
>
> printf("%a\n", DBL_EPSILON);
>
> The answer was "0x1p-52".
>
> A search of comp.lang.python shows that I was not alone. Here are some 
> ideas.
>
> 1. Add to Python the constants in "float.h" and "limits.h".

Where?

> 2. Add the C99 "%a" format to the "%" operator for strings and allow it 
> in floating point literals.

Is there an implementation of this somewhere?  We mostly certainly are
not demanding a C99 compiler yet.

> 3. Add full "tostring" and "fromstring" capabilities for Python numeric 
> types. "tostring(x)" would return a string containing the binary 
> representation of x. For example, if x is a Python float, "tostring(x)" 
> would have eight characters. "fromstring(s, atype)" does the reserve, so
>      fromstring(tostring(x), type(x)) == x

We have this already in the struct module.  I have a patch that should
improve the robustness of these functions on IEEE-754 platforms in the
face of special values that you can review if you like:

    http://python.org/sf/1181301

(my not-so-recent anguished "will one of you bastards please review
this and/or 1180995 for me?" still applies, btw)

> 4. Add some functions that process floating point types at a low level. 
> I suggest borrowing from C
>      (mantissa, exponent) = frexp(x)
> where mantissa is a float and exponent is an int. The mantissa can be 
> 0.0 or 0.5 <= mantissa < 1.0. Also x = mamtissa * 2**exponent. If
> x == 0.0, the function returns (0.0, 0). (This is almost a quote from 
> Harbison and Steele.)

>>> math.frexp(math.pi)
(0.78539816339744828, 2)

What am I missing?

> 5. Add the C99 constants and functions involving special floating point 
> values: "FP_INFINITE", "FP_NAN", "FP_NORMAL", "FP_SUBNORMAL", "FP_ZERO", 
> "fpclassify", "isfinite", "isinf", "isnan", "isnormal", "signbit", 
> "copysign", "nan", "nextafter", and "nexttoward". There has been 
> controversy about these in the past, but I am in favor of them. The 
> documentation should discuss portability.

If you can supply a patch to make all the compilers out there behave
with respect to these functions, I'll be impressed (they seem to exist
on Mac OS X 10.3, dunno if they work though :).

Cheers,
mwh

-- 
  If you're talking "useful", I'm not your bot.
                                            -- Tim Peters, 08 Nov 2001


More information about the Python-Dev mailing list