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