简体   繁体   English

为什么“np.inf // 2”会导致 NaN 而不是无穷大?

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

I'm slightly disappointed that np.inf // 2 evaluates to np.nan and not to np.inf , as is the case for normal division.我有点失望np.inf // 2评估为np.nan而不是np.inf ,就像正常除法的情况一样。

Is there a reason I'm missing why nan is a better choice than inf ?我是否有理由错过为什么nan是比inf更好的选择?

I'm going to be the person who just points at the C level implementation without any attempt to explain intent or justification:我将成为仅指出 C 级别实施的人,而没有任何试图解释意图或理由的人:

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

It looks like in order to calculate divmod for floats (which is called when you just do floor division ) it first calculates the modulus and float('inf') %2 only makes sense to be NaN , so when it calculates vx - mod it ends up with NaN so everything propagates nan the rest of the way.看起来为了计算浮点数的divmod (当你做地板除法时调用它)它首先计算模数和float('inf') %2只有NaN才有意义,所以当它计算vx - mod它以NaN结束,所以一切都传播到 rest 的方式。

So in short, since the implementation of floor division uses modulus in the calculation and that is NaN , the result for floor division also ends up NaN所以简而言之,由于地板除法的实现在计算中使用模数,即NaN ,地板除法的结果也以NaN结尾

Floor division is defined in relation to modulo, both forming one part of the divmod operation.楼层划分是根据模数定义的,两者都构成了 divmod 操作的一部分。

Binary arithmetic operations 二进制算术运算

The floor division and modulo operators are connected by the following identity: x == (x//y)*y + (x%y) .底除法和取模运算符通过以下恒等式连接: 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) .楼层除法和取模也与内置的 function divmod(): divmod(x, y) == (x//y, x%y)连接。

This equivalence cannot hold for x = inf — the remainder inf % y is undefined — making inf // y ambiguous.对于x = inf ,这个等式不能成立——余数inf % y是未定义的——使得inf // y模棱两可。 This means nan is at least as good a result as inf .这意味着nan至少与inf一样好。 For simplicity, CPython actually only implements divmod and derives both // and % by dropping a part of the result — this means // inherits nan from divmod.为简单起见, CPython 实际上只实现了 divmod 并通过删除部分结果来派生 // 和 % ——这意味着//从 divmod 继承了nan

Infinity is not a number.无穷大不是一个数字。 For example, you 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.所以你会遇到这样的限制,因为 NumPy 是一个数值数学 package。 I suggest using a symbolic math package like SymPy which can handle many different expressions using infinity:我建议使用符号数学 package 之类的SymPy ,它可以使用无穷大处理许多不同的表达式:

import sympy as sp

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM