Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Diagnosis of floating-point overflows in C++ programs

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?

like image 615
clstaudt Avatar asked Feb 15 '13 14:02

clstaudt


People also ask

What can cause overflow in floating point numbers?

In general, a floating point overflow occurs whenever the value being assigned to a variable is larger than the maximum possible value for that variable.

How do you detect overflows?

The rules for detecting overflow in a two's complement sum are simple: If the sum of two positive numbers yields a negative result, the sum has overflowed. If the sum of two negative numbers yields a positive result, the sum has overflowed. Otherwise, the sum has not overflowed.

How do I fix floating point exception?

You can run into computations that lead to division by zero when you are working on an array using a for loop. One of the best ways to do this is to check if the denominator is zero before you divide. This will avoid the floating-point exception error.

What is underflow and overflow of data and how it affects floating point values in C?

Integer Overflow occurs when we attempt to store a value greater than the data type's largest value. Similarly, Integer Underflow occurs when we attempt to store a value that is less than the least value of the data type. We can detect these overflows and underflows either mathematically (or) programmatically.


1 Answers

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.

like image 176
Josh Kelley Avatar answered Sep 23 '22 02:09

Josh Kelley