Diagnosis of floating-point overflows in C++ programs
c++, double, floating-point, numeric, overflow
Solution
If you enable floating point exceptions, then the FPU can throw an exception on overflow. How exactly this works is operating system dependent. For example:
- On Windows, you can use _control87 to unmask _EM_OVERFLOW so that you'll get a C++ exception on overflow.
- On Linux, you can use feenableexcept to enable exceptions on FE_OVERFLOW so that you'll get a SIGFPE on overflow. For example, to enable all exceptions, call `feenableexcept(FE_ALL_EXCEPT)` in your `main`. To enable overflow and divide by zero, call `feenableexcept(FE_OVERFLOW | FE_DIVBYZERO)`.
Note that, in all cases, third-party code may disable exceptions that you've enabled; this is probably rare in practice.
This is probably not quite as nice as Valgrind, since it's more of a drop-to-debugger-and-manually-inspect than it is a get-a-nice-summary-at-the-end, but it works.
Problem
I have a situation in which some numerical results (involving floating point arithmetic with `double` and `float`) become incorrect for large input sizes, but not for small ones. In general, I would like to know which tools are available to diagnose conditions such as numerical overflows and problematic loss of precision. In other words: Is there a tool which complains about overflows etc. the same way valgrind complains about memory errors?