NaN 上的宇宙飞船运算符
Spaceship Operator on NaN
C++ 在进行 space-ship 比较操作时如何处理浮点 NaN?我们知道通常的比较总是 return false,那么这与 NaN 有何不同?
std::numeric_limits<double>::quiet_NaN() <=> std::numeric_limits<double>::quiet_NaN()
根据 cppreference,对于内置 <=>
运算符的浮点参数:
[...] the operator yields a prvalue of type std::partial_ordering
. The expression a <=> b
yields
std::partial_ordering::less
if a
is less than b
std::partial_ordering::greater
if a is greater than b
std::partial_ordering::equivalent
if a
is equivalent to b
(-0 <=> +0
is equivalent)
std::partial_ordering::unordered
(NaN <=>
anything is unordered)
因此,简而言之,将 <=>
应用于 NaN 的浮点值会导致 std::partial_ordering::unordered
。
当计算像 a <=> b == 0
或 a <=> b < 0
这样的表达式时,如果 a
或 b
是 NaN 那么整个表达式 returns false
,这来自 NaN 的内置行为 (source)。当然,std::partial_ordering::unordered == std::partial_ordering::unordered
成立,否则这种类型不会很有用。
如果您能以其他方式保证不存在病态浮点值,请查看 的浮点包装器,其比较结果为 std::strong_ordering
.
C++ 在进行 space-ship 比较操作时如何处理浮点 NaN?我们知道通常的比较总是 return false,那么这与 NaN 有何不同?
std::numeric_limits<double>::quiet_NaN() <=> std::numeric_limits<double>::quiet_NaN()
根据 cppreference,对于内置 <=>
运算符的浮点参数:
[...] the operator yields a prvalue of type
std::partial_ordering
. The expressiona <=> b
yields
std::partial_ordering::less
ifa
is less thanb
std::partial_ordering::greater
if a is greater thanb
std::partial_ordering::equivalent
ifa
is equivalent tob
(-0 <=> +0
is equivalent)std::partial_ordering::unordered
(NaN<=>
anything is unordered)
因此,简而言之,将 <=>
应用于 NaN 的浮点值会导致 std::partial_ordering::unordered
。
当计算像 a <=> b == 0
或 a <=> b < 0
这样的表达式时,如果 a
或 b
是 NaN 那么整个表达式 returns false
,这来自 NaN 的内置行为 (source)。当然,std::partial_ordering::unordered == std::partial_ordering::unordered
成立,否则这种类型不会很有用。
如果您能以其他方式保证不存在病态浮点值,请查看 std::strong_ordering
.