tags:

views:

58

answers:

1

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.

+2  A: 

Comparing double values 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) < EPSILON where EPSILON will be something 10^-5.

Naveen
I understand. This is a simple example. I usually compare by comparing the absolute error to an epsilon. But when I substitute that logic, in this case, I still get different outputs. This really is driving me nuts. I am looking into potential buffer overflow issues..
@Naveen you were right. There was a bug in my floating point comparison function. I fixed it and it works ok now. thanks!