Exact integer-valued floats

Jussi Piitulainen jpiitula at ling.helsinki.fi
Fri Sep 21 15:47:07 EDT 2012


Steven D'Aprano writes:

> 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?

There is a way to find the distance between two IEEE floats in "ulps",
or "units in the last position", computable from the bit pattern using
integer arithmetic. I think it's then also possible to find the next
float by adding one.

I don't have a link at hand, I'm too tired to search at the moment,
and I'm no expert on floats, but you might find an answer by looking
for ulps.

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

Come to think of it, the difference between adjacent floats is exactly
one ulp. Just use the right unit :)



More information about the Python-list mailing list