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

编程入门 行业动态 更新时间:2024-10-11 13:25:53
本文介绍了如何检测双精度浮点溢出和下溢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下变量:

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

更多推荐

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

本文发布于:2023-10-24 20:47:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524959.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:浮点   精度

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!