添加高精度浮点时出现异常 [重复]

Anomaly when adding floating points of high precision [duplicate]

提问人:Constantinos Glynos 提问时间:11/14/2023 更新时间:11/14/2023 访问量:66

问:

请看以下示例:

int main()
{
    float x = 1.0f;
    float a = 0.0000000000000001f; //16 floating point
    
    std::cout<<std::fixed;
    
    std::cout<< std::setprecision(16) <<  a + a <<std::endl;
    std::cout<< std::setprecision(16) <<  x + a + a <<std::endl;
}

打印的结果是:

0.0000000000000002 // OK
1.0000000000000000 // NOK ??? 

在线代码: https://rextester.com/ITHF23448

问题:为什么从第二次加法的结果中省略了 2?正确答案应该是 1.0000000000000002

顺便说一句,这个例子在 Python 中产生了相同的结果,所以我有一种感觉它与语言无关。

C++ 浮点 加法 精度

评论


答: 暂无答案