Why `divmod(float('inf'), 1) == (float('nan'), float('nan'))`

Terry Reedy tjreedy at udel.edu
Wed Sep 17 03:12:48 CEST 2014

On 9/16/2014 5:40 PM, cool-RR wrote:
> While debugging my code I found that the bug was because I assumed
> that something like `divmod(float('inf'), 1)` would be equal to
> `(float('inf'), float('nan'))`,  while Python returns `(float('nan'),
> float('nan'))`. Why does Python make the division result be NaN in
> this case? `float('inf') / 1` is still `float('inf')`.

For integers, divmod(x, y) is defined as (x // y, x % y) == ((x - x%y) 
// y, x % y) == ((x - x%y) / y, x % y).

For floats, Python is documented as using the third expression.

"Help on built-in function divmod in module builtins:
     divmod(x, y) -> (div, mod)
     Return the tuple ((x-x%y)/y, x%y).  Invariant: div*y + mod == x."

It does not really matter, however, as infinity cannot be 'floored' as 
required for //

 >>> math.floor(float('inf'))
Traceback (most recent call last):
   File "<pyshell#21>", line 1, in <module>
OverflowError: cannot convert float infinity to integer

and hence

 >>> float('inf') // 1.0

Terry Jan Reedy

More information about the Python-list mailing list