检查C++中double等于负无穷大的最佳方法

evo*_*obe 2 c++ numerical numerical-computing c++11

我发现了这个:http://en.cppreference.com/w/cpp/numeric/math/isinf但它似乎检查正无穷大.我只想检查一个值是否恰好等于负无穷大,或者换句话说是log(0)

谢谢你的回答!根据下面的响应,这里有一些代码显示了什么有效.

#include <iostream>
#include <cmath>
#include <math.h>
using namespace std;
int main()
{
    double c = std::log(0.0);
    auto result = c == - INFINITY;
    cout << result << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

小智 12

明显和明确的怎么样?

要检查a double x是负无穷大,请检查

x == -std::numeric_limits<double>::infinity()
Run Code Online (Sandbox Code Playgroud)

如果x是某些其他浮点类型,请double根据需要进行更改.

std::numeric_limits在标准标题中定义<limits>.别忘了将它添加到您的#include列表中.


Pas*_*uoq 9

x == -1.0 / 0.0

如果iff x为负无穷大,则此表达式的计算结果为true .

如果您愿意包含cmath,那么x == - INFINITY更具可读性.

假设浮点类型映射到IEEE 754格式,那么它们中的每一个都有自己的无穷大.1.0 / 0.0double无限的.它的类型并不重要,INFINITY因为"通常的算术转换"将负责匹配左侧和右侧的类型==.