From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: (qmail 21966 invoked by alias); 4 Aug 2008 21:41:09 -0000 Received: (qmail 21955 invoked by uid 22791); 4 Aug 2008 21:41:09 -0000 X-Spam-Check-By: sourceware.org Received: from ik-out-1112.google.com (HELO ik-out-1112.google.com) (66.249.90.179) by sourceware.org (qpsmtpd/0.31) with ESMTP; Mon, 04 Aug 2008 21:40:22 +0000 Received: by ik-out-1112.google.com with SMTP id b32so2440670ika.0 for ; Mon, 04 Aug 2008 14:40:19 -0700 (PDT) Received: by 10.210.73.12 with SMTP id v12mr233229eba.101.1217886019727; Mon, 04 Aug 2008 14:40:19 -0700 (PDT) Received: from tmac.localnet ( [193.157.237.246]) by mx.google.com with ESMTPS id b33sm15874871ika.2.2008.08.04.14.40.05 (version=SSLv3 cipher=RC4-MD5); Mon, 04 Aug 2008 14:40:14 -0700 (PDT) From: Torquil Macdonald =?iso-8859-1?q?S=F8rensen?= To: gcc-help@gcc.gnu.org Subject: Optimization and double comparison Date: Mon, 04 Aug 2008 21:41:00 -0000 User-Agent: KMail/1.10.0 (Linux/2.6.26.080303-2; KDE/4.1.0; i686; ; ) MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: 7bit Content-Disposition: inline Message-Id: <200808042334.05408.torquil@gmail.com> X-IsSubscribed: yes Mailing-List: contact gcc-help-help@gcc.gnu.org; run by ezmlm Precedence: bulk List-Id: List-Archive: List-Post: List-Help: Sender: gcc-help-owner@gcc.gnu.org X-SW-Source: 2008-08/txt/msg00036.txt.bz2 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 #include 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); }