(C++) trying to make an exceptions for -1.#IND
Hey everyone,
I'm running lots of values through mathematical functions (doubles) and at some points I do get -1.#IND as a return (probably for deviding by 0). I would like to make exceptions for when this happens, but I'm not quite sure how to test for +-1.#IND....I tried comparing the value to itself as in if( x != x) ...but that didn't work.
How does one go about doing this?
Cheers,
Chris
Is that 1.#IND thing infinity? If so, then:
#include <limits>inline bool ouch(double x){ return x == numeric_limits<double>::infinity() || x ==-numeric_limits<double>::infinity();}
"fpclassify" is probably what you are looking for. Or at least searching for that will show you what else there is in that area that is that may be what you want.
Or do you mean to enable the platform to generate floating-point exceptions itself? If so, what compiler?
Or do you mean to enable the platform to generate floating-point exceptions itself? If so, what compiler?
Quote:SiCrane
-1.#IND is NaN, though division by 0 will usually get you an infinity rather than a NaN.
That's right, though in the special case of .0/.0, you'll get a NaN.
Quote:Original post by loufoque
you can't compare NaNs.
As I said you need to use isnan and isinf, which are in <cmath>.
In principle, that is, if a compiler correctly implements NaN behaviour, comparison with NaNs is defined in the following way:
Quote:wikipedia
A NaN does not compare equal to any floating-point number or NaN, even if the latter has an identical representation. One can therefore test whether a variable has a NaN value by comparing it to itself, thus if x = x gives false then x is a NaN code. Likewise x \neq x gives true.
Here's a small example:
#include <iostream>int main () { const float NaN = 0.0f / 0.0f, ; std::cout << "NaN : " << NaN << " (expected NaN)\n" << "NaN == NaN : " << (NaN == NaN) << " (expected 0)\n" << "NaN != NaN : " << (NaN != NaN) << " (expected 1)\n" << "NaN < 0.0 : " << (NaN < 0.0f) << " (expected 0)\n" << "NaN != 0.0 : " << (NaN != 0.0f) << " (expected 1)\n" << "NaN == 0.0 : " << (NaN == 0.0f) << " (expected 0)\n" << "NaN > 0.0 : " << (NaN > 0.0f) << " (expected 0)\n" << std::flush ;}
With g++ 3.x and standard flags, I (correctly) get
NaN : NaN (expected NaN) NaN == NaN : 0 (expected 0) NaN != NaN : 1 (expected 1) NaN < 0.0 : 0 (expected 0) NaN != 0.0 : 1 (expected 1) NaN == 0.0 : 0 (expected 0) NaN > 0.0 : 0 (expected 0)
But yes, one shall better use is_nan()'esque functions.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement