Skip to content

Support hexadecimal floating point literals #114667

@skirpichev

Description

@skirpichev

Feature or enhancement

Proposal:

The Python supports only decimal floating point literals. But underlying hardware based floating point numbers are binary, not decimal, and conversion to and from decimal representation is delicate: it's not obvious which binary floating point number represent a given decimal literal.

Exact floating point representations are especially important for reproducible results --- for instance, while testing "borderline cases" in algorithms. Because of this, many contemporary languages (e.g. C, Go, Julia, Java) introduce hexadecimal floating point literals in source code. This format also common in the numerical analysis community (see e.g. this example or the MPFR library).

Lets accept exact floating point literals (beyond simple cases like 0.25) as first-class citizens in the language! Right now the Python include support for hexadecimal floats via float.fromhex() and float.hex() methods, which extensively used in it's test suite (e.g. to test math and random modules). But using the class method to create exact floating point values much less convenient, especially doing interactive work:

>>> float.fromhex('0x1.ffffp10')
2047.984375
>>> 0x1.ffffp10
2047.984375
>>> -0x1p-1074
-5e-324
>>> 0x1.1
1.0625
>>> float('0x1.1')
1.0625

As it was noted in the discussion thread, this feature might require a PEP. In this case I'm looking for a sponsor. Meanwhile, I'll make a draft pr, to not trigger review requests.

PEP draft: skirpichev/peps#4

Related issue: #113804

Has this already been discussed elsewhere?

I have already discussed this feature proposal on Discourse

Links to previous discussion of this feature:

https://discuss.python.org/t/41848

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions