Exact integer-valued floats

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Sep 21 13:29:13 EDT 2012


Python floats can represent exact integer values (e.g. 42.0), but above a 
certain value (see below), not all integers can be represented. For 
example:

py> 1e16 == 1e16 + 1  # no such float as 10000000000000001.0
True
py> 1e16 + 3 == 1e16 + 4  # or 10000000000000003.0
True

So some integers are missing from the floats. For large enough values, 
the gap between floats is rather large, and many numbers are missing:

py> 1e200 + 1e10 == 1e200
True

The same applies for large enough negative values.

The question is, what is the largest integer number N such that every 
whole number between -N and N inclusive can be represented as a float?

If my tests are correct, that value is 9007199254740992.0 = 2**53.

Have I got this right? Is there a way to work out the gap between one 
float and the next?

(I haven't tried to exhaustively check every float because, even at one 
nanosecond per number, it will take over 200 days.)


-- 
Steven



More information about the Python-list mailing list