简体   繁体   English

在C ++中比较无穷大和无穷大

[英]Compare infinity with infinity in C++

Suppose I have two variables which are both set to infinity 假设我有两个变量都设置为无穷大

double l = std::numeric_limits<double>::infinity();
double r = std::numeric_limits<double>::infinity();

At another point in the code, I have a comparison of these two variables 在代码的另一点,我对这两个变量进行了比较

if (l < r) {}

Is the result of this comparison properly defined in the library? 这个比较的结果是在库中正确定义的吗? (Within the logic of my program, I would expect the result to be false .) (在我的程序逻辑中,我希望结果是false 。)

(Within the logic of my program, I would expect the result to be false .) (在我的程序逻辑中,我希望结果是false 。)

According to this : 根据这个

In comparison operations, positive infinity is larger than all values except itself and NaN 在比较操作中,正无穷大大于除自身和NaN之外的所有值

So you are indeed correct. 所以你确实是对的。

Note that this might not be valid if your compiler uses a different standard than IEEE 754, so make sure that std::numeric_limits<double>::is_iec559; 请注意,如果编译器使用的标准与IEEE 754不同,则可能无效,因此请确保std::numeric_limits<double>::is_iec559; returns true when in doubt. 有疑问时返回true

C++ does not require an implementation to support infinity in its floating-point types. C ++不需要实现来支持其浮点类型的无穷大。 However, if an implementation does support infinity, we can expect that infinity < infinity is false. 但是,如果实现确实支持无穷大,我们可以预期infinity < infinity是错误的。 C++ implicitly assumes normal mathematics—it does not define mathematical addition, multiplication, division, cosine, logarithm, and so on, but just assumes mathematics is background information known to the reader. C ++隐含地假设了正常的数学 - 它没有定义数学加法,乘法,除法,余弦,对数等等,而只是假设数学是读者已知的背景信息。

Mathematicians do distinguish different types of infinities, but C++ makes no provision for this; 数学家确实区分了不同类型的无穷大,但C ++没有为此做出规定; it provides only one positive infinity and one negative infinity. 它只提供一个正无穷大和一个负无穷大。 So it is clear they are simple extensions of the real numbers. 所以很明显它们是实数的简单扩展。

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

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