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

cool-RR ram.rachum at gmail.com
Wed Sep 17 10:55:32 EDT 2014


Terry, that doesn't really answer the question "why", it just pushes it back to the documentation. Is there a real answer why? Why return NaN when Inf would make mathematical sense?

On Wednesday, September 17, 2014 4:13:38 AM UTC+3, Terry Reedy wrote:
> 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(...)
> 
>      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>
> 
>      math.floor(float('inf'))
> 
> OverflowError: cannot convert float infinity to integer
> 
> 
> 
> and hence
> 
> 
> 
>  >>> float('inf') // 1.0
> 
> nan
> 
> 
> 
> -- 
> 
> Terry Jan Reedy




More information about the Python-list mailing list