public inbox for gcc-help@gcc.gnu.org
 help / color / mirror / Atom feed
* Optimization and double comparison
@ 2008-08-04 21:41 Torquil Macdonald Sørensen
  2008-08-04 22:21 ` Brian Dessent
  0 siblings, 1 reply; 4+ messages in thread
From: Torquil Macdonald Sørensen @ 2008-08-04 21:41 UTC (permalink / raw)
  To: gcc-help

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);
}

^ permalink raw reply	[flat|nested] 4+ messages in thread

end of thread, other threads:[~2008-08-05 15:22 UTC | newest]

Thread overview: 4+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2008-08-04 21:41 Optimization and double comparison Torquil Macdonald Sørensen
2008-08-04 22:21 ` Brian Dessent
2008-08-05  8:19   ` Torquil Macdonald Sørensen
2008-08-05 15:22     ` Bob Plantz

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).