如果 numeric_limits::has_infinity 为 false,建议的解决方法是什么?
我需要在 Linux 上的 C++ 应用程序中检查双精度值是否为无穷大。 在大多数平台上,这是通过与 std::numeric_limitsstd::numeric_limits
为 false。
您会为这些平台推荐什么解决方法?
I need to check a double value for infinity in a C++ app on Linux. On most platforms this works by comparing with std::numeric_limits<double>::infinity()
. However, on some old platforms (RedHat 9 for example, with gcc 3.2.2) this is not available, and std::numeric_limits<double>::has_infinity
is false there.
What workaround would you recommend for those platforms?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您使用 IEEE 754 算术(几乎可以肯定),无穷大是定义明确的值,并且对所有算术运算都有定义的结果。 特别是,
正无穷大和负无穷大以及 NaN 值是唯一符合此条件的值。 NaN 是特殊的“非数字”值,用于指示函数的域错误,例如
sqrt(-1)
。 另外:NaN 是唯一符合此条件的值。
因此:
当且仅当
x
为正无穷大或负无穷大时,才会返回 true。 添加x > 的测试 0
如果您只想检查正无穷大。If you're using IEEE 754 arithmetic, as you almost certainly are, infinities are well defined values and have defined outcomes for all arithmetic operations. In particular,
Positive and negative infinity and
NaN
values are the only values for which this is true. NaNs are special "not-a-number" values used to indicate domain errors of functions, e.g.sqrt(-1)
. Also:NaN
s are the only values for which this is true.Therefore:
will return true if and only if
x
is either positive or negative infinity. Add a test forx > 0
if you only want to check for positive infinity.在大多数情况下,std::numeric_limits::max() 可以有效替代 std::numeric_limits::infinity()。
但是,您在使用它时必须更加小心。 对于溢出,我相信您必须手动检测溢出,并在检测到溢出时将结果显式设置为最大值。
For most cases, std::numeric_limits::max() can be a valid replacement for std::numeric_limits::infinity().
You would have to be more careful about using it, however. With overflows I believe you would have to manually detect the overflow and set the result to the max explicitly if an overflow is detected.
好吧,我现在已经在该特定机器上使用了 INFINITY 和 NAN 宏 - 似乎工作正常。 它们来自
math.h
。Ok, I have now resorted to using the
INFINITY
andNAN
macros on that particular machine - seems to work fine. They come frommath.h
.