8

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;
}
evolvedmicrobe
  • 2,672
  • 2
  • 22
  • 30

2 Answers2

23

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.

9

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 ==.

Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281
  • 1
    if you don't want to include ``, you can use these macros: `#define POSINF (1.0 / 0.0)`, `#define NEGINF ((-1.0) / 0.0)`, and `#define NAN (0.0 / 0.0)`. You'll probably get some warnings about overflow for constants, but they should work. – triple_r Feb 23 '15 at 21:34
  • I didn't realize -Inf == -Inf, that actually looks a bit like a bug to me, but if it works, works for me! – evolvedmicrobe Feb 23 '15 at 21:38
  • This is platform-dependent, no? – Lightness Races in Orbit Feb 23 '15 at 21:40
  • @LightnessRacesinOrbit It is, but any platform that takes IEEE 754 seriously (in C++, `std::numeric_limits::is_iec559` can be used to confirm this) would work as in this answer, because IEEE 754 defines 1 / 0 as +inf, -(+inf) as -inf, and the equality x == -inf to be true iff x is -inf. The only question is whether a platform implements IEEE 754. C++ also allows extra precision for intermediate results, but inf is inf at any precision. – Pascal Cuoq Feb 23 '15 at 22:22
  • Yeah so you should mention that in your answer :) And the OP should check for `std::numeric_limits::is_iec559`. – Lightness Races in Orbit Feb 23 '15 at 22:30
  • Visual Studio doesn't compile `1.0 / 0.0`, it complains about division by zero (at least with default settings). – Duke Oct 21 '19 at 19:11