kiriloff
kiriloff

Reputation: 26333

c++ test whether double is #INF

I would like to isolate the behavior when some double value is a NaN or an #INF. To detect a NaN, I test

doubleVal != doubleVal

What about an #INF? Will this test be true when the doubleVal is an #INF?

Upvotes: 1

Views: 5353

Answers (3)

James
James

Reputation: 25513

If you're not using c++11, then you'll need <boost/math/special_functions/fpclassify.hpp> instead of <cmath>, with corresponding namespace change.

#include <cmath> // or <boost/math/special_functions/fpclassify.hpp>
// ...

    if(isinf(num)){
        // ...
    }

Upvotes: 3

rubenvb
rubenvb

Reputation: 76519

How about multiplication by 1. once you're sure it's not NaN?

http://ideone.com/97FNu

You could also use isinf and isnan, but those might incur some overhead depending on their implementation.

A third alternative is using the C max value macros (or equivalent std::numeric_limits):

 bool is_inf_or_nan(double x) 
{
    return !(x <= DBL_MAX && x >= -DBL_MAX); 
}    

Upvotes: 4

Anonymous
Anonymous

Reputation: 18631

There is also a header-only library present in Boost that have neat tools to deal with floating point datatypes

#include <boost/math/special_functions/fpclassify.hpp>

You get the following functions:

template <class T> bool isfinite(T z);
template <class T> bool isinf(T t);
template <class T> bool isnan(T t);
template <class T> bool isnormal(T t);

Upvotes: 2

Related Questions