c++双精度循环

C++ Looping with doubles

本文关键字:循环 双精度 c++      更新时间:2023-10-16

为什么PRINT THIS在下面的代码中从不打印?我已经计算过了<<Shiftx和shifty确保在某个时刻,它们都是0.3。

for(double shifty=0; shifty < 2; shifty+=.1) {
    for(double shiftx=0; shiftx < 2; shiftx +=.1) {
        if((shiftx == 0.3) && (shifty == 0.3)) {
            cout << "PRINT THIS" << endl;
        }
    }    
}

黄金法则是:在浮点数中避免相等检验。

0.1和0.3都不能精确表示。

标准阅读:What Every Computer Scientist Should Know About Floating-Point Arithmetic

要解决您的特定问题,您应该使用整数类型进行迭代和比较。只有在实际需要时才转换为浮点类型。例如:

for(int shifty=0; shifty < 20; shifty++) {
    for(int shiftx=0; shiftx < 20; shiftx++) {
        double shifty_double = shifty * 0.1;
        double shiftx_double = shiftx * 0.1;
        if((shiftx == 3) && (shifty == 3)) {
            cout << "PRINT THIS" << endl;
        }
    }    
}

这可能是由于使用double时的舍入错误,因为0.3实际上并没有在内部完全存储为0.3。

比较双精度数的一种方法是允许在比较中出现一些错误。示例

if(abs(shiftx - shifty) < 0.000001)