How to detect double precision floating point overflow and underflow?

A lot depends on context. To be perfectly portable, you have to
check before the operation, e.g. (for addition):

if ( (a < 0.0) == (b < 0.0)
    && std::abs( b ) > std::numeric_limits<double>::max() - std::abs( a ) ) {
    //  Addition would overflow...
}

Similar logic can be used for the four basic operators.

If all of the machines you target support IEEE (which is
probably the case if you don’t have to consider mainframes), you
can just do the operations, then use isfinite or isinf on
the results.

For underflow, the first question is whether a gradual underflow
counts as underflow or not. If not, then simply checking if the
results are zero and a != -b would do the trick. If you want
to detect gradual underflow (which is probably only present if
you have IEEE), then you can use isnormal—this will
return false if the results correspond to gradual underflow.
(Unlike overflow, you test for underflow after the operation.)

Leave a Comment