Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trace a NaN in C++

I am going to do some math calculations using C++ . The input floating point number is a valid number, but after the calculations, the resulting value is NaN. I would like to trace the point where NaN value appears (possibly using GDB), instead of inserting a lot of isNan() into the code. But I found that even code like this will not trigger an exception when a NaN value appears.

double dirty = 0.0; double nanvalue = 0.0/dirty; 

Could anyone suggest a method for tracing the NaN or turning a NaN into an exception?

like image 369
user1492900 Avatar asked Sep 01 '10 07:09

user1492900


People also ask

How is NaN represented in C?

— Macro: float NAN An expression representing a value which is “not a number”. This macro is a GNU extension, available only on machines that support the “not a number” value—that is to say, on all machines that support IEEE floating point. You can use '#ifdef NAN' to test whether the machine supports NaN.

How do I know if my float is NaN?

To check whether a floating point or double number is NaN (Not a Number) in C++, we can use the isnan() function. The isnan() function is present into the cmath library. This function is introduced in C++ version 11.


2 Answers

Since you mention using gdb, here's a solution that works with gcc -- you want the functions defined in fenv.h :

#define _GNU_SOURCE #include <fenv.h> #include <stdio.h>  int main(int argc, char **argv) {    double dirty = 0.0;     feenableexcept(FE_ALL_EXCEPT & ~FE_INEXACT);  // Enable all floating point exceptions but FE_INEXACT    double nanval=0.0/dirty;    printf("Succeeded! dirty=%lf, nanval=%lf\n",dirty,nanval); } 

Running the above program produces the output "Floating point exception". Without the call to feenableexcept, the "Succeeded!" message is printed.

If you were to write a signal handler for SIGFPE, that might be a good place to set a breakpoint and get the traceback you want. (Disclaimer: haven't tried it!)

like image 52
Jim Lewis Avatar answered Sep 23 '22 04:09

Jim Lewis


In Visual Studio you can use the _controlfp function to set the behavior of floating-point calculations (see http://msdn.microsoft.com/en-us/library/e9b52ceh(VS.80).aspx). Maybe there is a similar variant for your platform.

like image 27
Patrick Avatar answered Sep 20 '22 04:09

Patrick