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

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

我有以下变量:

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(即如果您不必考虑大型机,可能就是这种情况),您可以只做操作,然后使用 isfinite 或 isinf 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.)

更多推荐

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

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

发布评论

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

>www.elefans.com

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