如何检测双精度浮点溢出和下溢? [英] How to detect double precision floating point overflow and underflow?

查看:703
本文介绍了如何检测双精度浮点溢出和下溢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下变量:

double dblVar1;
double dblVar2;

它们可能具有大值,但小于 double 最大。

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(这是
,如果你不必考虑大型机的情况下),你
只能做操作,然后使用 isfinite isinf
上的结果。

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

这篇关于如何检测双精度浮点溢出和下溢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆