开发者

C++ Looping with doubles

开发者 https://www.devze.com 2023-03-28 06:24 出处:网络
Why is PRINT THIS in the code below never printing? I\'ve already cout << shiftx and shifty to make sure that at some point, they both are 0.3.

Why is PRINT THIS in the code below never printing? I've already cout << shiftx and shifty to make sure that at some point, they both are 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;
        }
    }    
}


The golden rule is: avoid equality tests in floating-point.

Neither 0.1 nor 0.3 can be exactly represented.

Standard reading: What Every Computer Scientist Should Know About Floating-Point Arithmetic.

To solve your particular problem, you should iterate and perform comparisons using integer types. Only convert to floating-point types when you actually need to. e.g.:

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;
        }
    }    
}


This is probably due to rounding errors when using doubles since 0.3 isn't actually stored as exactly 0.3 internally.

A way to compare doubles would be to allow for some error in the comparison. Example

if(abs(shiftx - shifty) < 0.000001) 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号