Optimization and double comparison

Torquil Macdonald Sørensen torquil@gmail.com
Mon Aug 4 21:41:00 GMT 2008


Hi, is it expected that the attached program only works when no optimization 
is used? I do not understand why the if-test is ever entered in this program. 
The variables that are compared should be exactly the same, since one is used 
to set the value of the other another place in the program. I will attach the 
whole program below.

In short, how can it be that an if-test of the following form can print two 
exactly equal numbers?:

if( a != b) {
	cout << setprecision(70);
	cout << a << " " << b << endl;
} 

Btw, I know that normally one should do a comparison within a certain error 
when comparing doubles, but I am only interested in how the if-test above can 
print two equal numbers?

Here is the program (the if-test is entered when N=4, but not when N=2,3). In 
short, first pot[m][n] is set using calc(m,n), but afterwards the if-test says 
that they are different, if I compile with -O1:

#include <iostream>
#include <iomanip>

using namespace std;

const int M = 2, N = 4;

double calc(const int m, const int n)
{
	double pot = 0.0;
	for(int n2 = 0; n2 < n; ++n2) {
		pot += 0.1;
	}
	return(pot);
}

void check(double pot[][N])
{
	for(int m = 0; m != M; ++m) {
		for(int n = 0; n != N; ++n) {
			cout << "n = " << n << endl;
			if( calc(m,n) != pot[m][n] ) {
				cout << "Error!" << endl;
				cout << setprecision(70);
				cout << pot[m][n] << " and " << calc(m,n) << endl;
			}
		}
	}
}

int main()
{
	double pot[M][N];

	for(int m = 0; m != M; ++m) {
		for(int n = 0; n != N; ++n) {
			pot[m][n] = calc(m,n);
		}
	}

	check(pot);

	return(0);
}



More information about the Gcc-help mailing list