Is it safe to assume floats always have a 53-bit mantissa?

Marko Rauhamaa marko at pacujo.net
Wed Dec 30 09:19:30 EST 2015


Steven D'Aprano <steve at pearwood.info>:

> Nevertheless, it's well known (in the sense that "everybody knows")
> that Python floats are equivalent to C 64-bit IEEE-754 doubles. How
> safe is that assumption?

You'd need to have it in writing, wouldn't you?

The only spec I know of promises no such thing:

   Floating point numbers are usually implemented using double in C;
   information about the precision and internal representation of
   floating point numbers for the machine on which your program is
   running is available in sys.float_info.

   <URL: https://docs.python.org/3/library/stdtypes.html#typesnumeric>

> As an optimization, I want to write:
>
> def func(n):
>     if n <= 2**53:
>         # use the floating point fast implementation
>     else:
>         # fall back on the slower, but exact, int algorithm
>
> [...]
>
> But I wonder whether I need to write this instead?
>
> def func(n):
>     if n <= 2**sys.float_info.mant_dig:
>         # ...float
>     else:
>         # ...int
>
> I don't suppose it really makes any difference performance-wise, but I
> can't help but wonder if it is really necessary. If
> sys.float_info.mant_dig is guaranteed to always be 53, why not just
> write 53?

Mainly because

   2**sys.float_info.mant_dig

looks much better than

   2**53


Marko



More information about the Python-list mailing list