[Python-Dev] Adding DBL_MANTISSA and such to Python
Edward C. Jones
edcjones at comcast.net
Thu May 5 05:37:20 CEST 2005
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".
2. Add the C99 "%a" format to the "%" operator for strings and allow it
in floating point literals.
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
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.)
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.
More information about the Python-Dev
mailing list