如何检测双精度浮点上溢和下溢?

2022-01-09 00:00:00 floating-point c++

我有以下变量:

double dblVar1;
double dblVar2;

它们的值可能很大,但小于 double max.

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);

在以上所有内容中,我必须检查上溢和下溢.如何在 C++ 中实现这一点?

In all above I have to check overflow and underflow. How can I achieve this in C++?

推荐答案

很大程度上取决于上下文.要完美便携,您必须检查之前操作,例如(补充):

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.

如果您所针对的所有机器都支持 IEEE(即如果您不必考虑大型机,可能就是这种情况),您可以只做操作,然后使用 isfiniteisinf on结果.

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.

对于下溢,第一个问题是是否逐渐下溢算不算下溢.如果没有,那么只需检查是否结果为零, a != -b 可以解决问题.如果你想检测逐渐下溢(这可能只存在于你有 IEEE),那么你可以使用 isnormal—这将如果结果对应于逐渐下溢,则返回 false.(与溢出不同,您在 操作之后测试下溢.)

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.)

相关文章