I am having a very strange problem in a simple program and have been unable to reach any logical conclusion. When I redirect output from my program to a file, then I get a different result that I get when printing to stdout. When I print to a file, the result is correct. I don’t understand why it would be different in the first place. Here is a snippet. Any ideas?
for (int i = 1; i <= N; i++) {
double x = i*h;
for (int j = 1; j <= N; j++) {
double y = j*h;
double bi = h*h*f(x,y);
if (x+h == 1.0) {
bi += boundary_f(1,y);
}
if (y+h == 1.0) {
bi += boundary_f(x,1);
}
cout << "i=" << i << "; j=" << j << "; b=" << bi << "\n";
b(k,1) = bi;
++k;
}
I get different results when printing to stdout and redirect to file! It seems like the conditions y+h==1.0 does not evaluate to true even when y+h is 1.0 when the output to stdout but when redirected to file, it evaluates correctly.
Comparing
doublevalues for absolute equality is bad. You can not gurantee whether the program enters ‘if’ condition or not. Instead what you can do is something like :fabs(y+h-1.0) < EPSILONwhere EPSILON will be something10^-5.