We have numerical code written in C++. Rarely but under certain specific inputs, some of the computations result in an 'nan' value.
Is there a standard or recommended method by which we can stop and alert the user when a certain numerical calculation results in an 'nan' being generated? (under debug mode).Checking for each result if it is equal to 'nan' seems impractical given the huge sizes of matrices and vectors.
How do standard numerical libraries handle this situation? Could you throw some light on this?
NaN is propagated, when applied to a numeric operation. So, it is enough to check the final result for being a NaN. As for, how to do it -- if building for >= C++11, there is std::isnan, as Goz noticed. For < C++11 - if want to be bulletproof - I would personally do bit-checking (especially, if there may be an optimization involved). The pattern for NaN is
? 11.......1 xx.......x
sign bit ^ ^exponent^ ^fraction^
where ? may be anything, and at least one x must be 1.
For platform dependent solution, there seams to be yet another possibility. There is the function feenableexcept
in glibc (probably with the signal
function and the compiler option -fnon-call-exceptions
), which turns on a generation of the SIGFPE
sinals, when an invalid floating point operation occure. And the function _control87
(probably with the _set_se_translator
function and compiler option /EHa
), which allows pretty much the same in VC.
Although this is a nonstandard extension originally from glibc, on many systems you can use the feenableexcept
routine declared in <fenv.h>
to request that the machine trap particular floating-point exceptions and deliver SIGFPE
to your process. You can use fedisableexcept
to mask trapping, and fegetexcept
to query the set of exceptions that are unmasked. By default they are all masked.
On older BSD systems without these routines, you can use fpsetmask
and fpgetmask
from <ieeefp.h>
instead, but the world seems to be converging on the glibc API.
Warning: glibc currently has a bug whereby (the C99 standard routine) fegetenv
has the unintended side effect of masking all exception traps on x86, so you have to call fesetenv
to restore them afterward. (Shows you how heavily anyone relies on this stuff...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With