tl;dr:
Recently I was writing some code that looks roughly like this:
double value= /* something */;
for(double step=1024;step>1e-8;step/=2)if(value-step>0){
value-=step;
// long long code to check condition satisfied
if(not ok)
value+=step;
}
While it gives correct answer locally on all sample test case, the result is wrong on Codeforces machine.
I had no idea what's going on, then decide to add a debug statement to the begin of the // long long code
block. However, when I add anything there (even cout<<"";
) the code gives the correct answer.
Initially I thought there's some undefined behavior, but I compiled with sanitization turned on, and there's no error reported.
Switching to another compiler works well on that particular test case.
Can you guess what could be the cause? (It's a bug in the code, not a compiler bug.)
(Of course if You're given the complete code and debug it for a while, you'll be able to find out the bug as well. The point here is that, can you guess what's the problem?)
Even if you knew about the behavior already (like me while debugging the code), I hope this blog can be useful to you when your code happen to have such a hard-to-explain behavior.