|
 |
Also check out:
https://www.johndcook.com/IEEE_exceptions_in_cpp.html
(I read a lot of John's blog posts - it's very interesting and informative)
Testing for NaNs and infinities
Next suppose you want to test whether a number is an infinity or a NaN. For
example, you may want to write to a log file print a debug message when a
numerical result goes bad, or you may want to execute some sort of alternate
logic in your code. There are simple, portable ways to get summary information
and more complicated, less portable ways to get more information.
First, the simple solution. If you want to test whether a double variable
contains a valid number, you can check whether x == x. This looks like it should
always be true, but it's not! Ordinary numbers always equal themselves, but NaNs
do not. I've used this trick on Windows, Linux, and Mac OSX. If you ever use
this trick, put big bold comments around your code so that some well-meaning
person won't come behind you and delete what he or she things is useless code.
Better yet, put the test in a well-documented function in a library that has
controlled access. The following function will test whether x is a (possibly
infinite) number.
bool IsNumber(double x)
{
// This looks like it should always be true,
// but it's false if x is a NaN.
return (x == x);
}
To test whether a variable contains a finite number, (i.e. not a NaN and not an
infinity) you can use code like the following.
bool IsFiniteNumber(double x)
{
return (x <= DBL_MAX && x >= -DBL_MAX);
}
Here DBL_MAX is a constant defined in float.h as the largest double that can be
represented. Comparisons with NaNs always fail, even when comparing to
themselves, and so the test above will fail for a NaN. If x is not a NaN but is
infinite, one of the two tests will fail depending on whether it is a positive
infinity or negative infinity.
Post a reply to this message
|
 |