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

How to detect double precision floating point overflow and underflow?(如何检测双精度浮点上溢和下溢?)
本文介绍了如何检测双精度浮点上溢和下溢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下变量:

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

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)