为什么“np.inf // 2”的结果是 NaN 而不是无穷大?

Why does “np.inf // 2” result in NaN and not infinity?

令我略感失望的是 np.inf // 2 的计算结果为 np.nan 而不是正常除法的 np.inf

为什么我想念 naninf 更好的选择?

我将成为 just points at the C level 在不尝试解释意图或理由的情况下实施的人:

*mod = fmod(vx, wx);
div = (vx - *mod) / wx;

看起来为了计算浮点数的 divmod(当你只是 do floor division 时调用)它首先计算模数并且 float('inf') %2 只有 NaN,所以当它计算 vx - mod 时,它以 NaN 结束,所以在剩下的过程中一切都会传播 nan。

所以简而言之,由于楼层划分的实现在计算中使用了模数,即NaN,楼层划分的结果最终也是NaN

楼层划分是根据模数定义的,两者都是 divmod 运算的一部分。

Binary arithmetic operations

The floor division and modulo operators are connected by the following identity: x == (x//y)*y + (x%y). Floor division and modulo are also connected with the built-in function divmod(): divmod(x, y) == (x//y, x%y).

对于 x = inf 这种等价性不成立——余数 inf % y 是未定义的——使得 inf // y 不明确。这意味着 nan 至少与 inf 一样好。为简单起见,CPython actually only implements divmod and derives both // and % by dropping a part of the result — 这意味着 // 从 divmod 继承 nan

无穷大不是数字。例如,您 can't even say that infinity - infinity is zero. So you're going to run into limitations like this because NumPy is a numerical math package. I suggest using a symbolic math package like SymPy 可以使用无穷大处理许多不同的表达式:

import sympy as sp

sp.floor(sp.oo/2)
sp.oo - 1
sp.oo + sp.oo