检测纯 C++ 中的精度损失

Ori*_*ent 5 c++ gcc g++

当您使用浮点数( 、floatdouble类型long double)进行操作时,是否可以检测到精度损失?说:

template< typename F >
F const sum(F const & a, F const & b)
{
    F const sum_(a + b);
    // The loss of precision must be detected (here or one line above) if some fraction bit is lost due to rounding
    return sum_;
}
Run Code Online (Sandbox Code Playgroud)

特别感兴趣的是x87 FPU 出现在目标架构上,但例程不干预asm纯 C++ 代码的情况。如果有的话,也接受C++11gnu++11特定功能。

Dre*_*ann 5

C++ 标准对浮点精度的概念非常模糊。没有完全符合标准的方法来检测精度损失。

GNU提供了启用浮点异常的扩展。您想要捕获的异常是FE_INEXACT.