Best way to check if double equals negative infinity in C++

廉价感情. 提交于 2020-01-11 06:42:26

问题


I found this: http://en.cppreference.com/w/cpp/numeric/math/isinf but it appears to check for either positive or negative infinity. I just want to check if a value is equal to exactly negative infinity, or in otherwords is log(0)

Thanks for answer! Based on response below, here is some code that shows what works.

#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;
}

回答1:


x == -1.0 / 0.0

This expression evaluates to true iff x is negative infinity.

If you are willing to include cmath, then x == - INFINITY is more readable.

Assuming that floating-point types are mapped to IEEE 754 formats, then each of them has its own infinity. 1.0 / 0.0 is a double infinity. It doesn't matter much the type of INFINITY because “usual arithmetic conversions” will take care of matching the types of the left- and right-hand-side of ==.




回答2:


How about the obvious and explicit?

To check that a double x is negative infinity, check

x == -std::numeric_limits<double>::infinity()

If x is some other floating-point type, change double as appropriate.

std::numeric_limits is defined in the standard header <limits>. Don't forget to add it to your #include list.



来源:https://stackoverflow.com/questions/28683702/best-way-to-check-if-double-equals-negative-infinity-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!