How to detect double precision floating point overflow and underflow?
c++, floating-point
Solution
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.)
Problem
I have following variables: ``` double dblVar1; double dblVar2; ``` They may have big values but less than `double` max. I have various arithmetic on above variables like addition, multiplication and power: ``` double dblVar3 = dblVar1 * dblVar2; double dblVar4 = dblVar1 + dblVar2; double dblVar5 = pow(dblVar1, 2); ``` In all above I have to check overflow and underflow. How can I achieve this in C++?