[Python-ideas] Hexadecimal floating literals

Nick Coghlan ncoghlan at gmail.com
Wed Sep 20 21:13:44 EDT 2017

On 21 September 2017 at 10:44, Chris Barker - NOAA Federal
<chris.barker at noaa.gov> wrote:
>> To sum up:
>> -  In some specific context, hexadecimal floating-point constants make it easy for the programmers to reproduce the exact value. Typically, a software engineer who is concerned about floating-point accuracy would prepare hexadecimal floating-point constants for use in a program by generating them with special software (e.g., Maple, Mathematica, Sage or some multi-precision library). These hexadecimal literals have been added to C (since C99), Java, Lua, Ruby, Perl (since v5.22), etc. for the same reasons.
>> - The exact grammar has been fully documented in the IEEE-754-2008 norm (section 5.12.13), and also in C99 (or C++17 and others)
>> - Of course, hexadecimal floating-point can be manipulated with float.hex() and float.fromhex(), *but* it works from strings, and the translation is done at execution-time...
> Right. But it addresses all of the points you make. The functionality
> is there. Making a new literal will buy a slight improvement in
> writability and performance.
> Is that worth much in a dynamic language like python?

I think so, as consider this question: how do you write a script that
accepts a user-supplied string (e.g. from a CSV file) and treats it as
hex floating point if it has the 0x prefix, and decimal floating point

You can't just blindly apply float.fromhex(), as that will also treat
unprefixed strings as hexadecimal:

>>> float.fromhex("0x10")
>>> float.fromhex("10")

So you need to do the try/except dance with ValueError instead:

        float_data = float(text)
    except ValueError:
        float_values = float.fromhex(text)

At which point you may wonder why you can't just write "float_data =
float(text, base=0)" the way you can for integers:

>>> int("10", base=0)
>>> int("0x10", base=0)

And if the float() builtin were to gain a "base" parameter, then it's
only a short step from there to allow at least the "0x" prefix on
literals, and potentially even "0b" and "0o" as well.

So I'm personally +0 on the idea - it would improve interface
consistency between integers and floating point values, and make it
easier to write correctness tests for IEEE754 floating point hardware
and algorithms in Python (where your input & output test vectors are
going to use binary or hex representations, not decimal).


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list