RE: [PHP-DEV] Problem with a if-statement

From: Date: Mon, 18 Oct 1999 12:54:58 +0000
Subject: RE: [PHP-DEV] Problem with a if-statement
Groups: php.dev 
Request: Send a blank email to php-dev+get-11739@lists.php.net to get a copy of this message
> I have a very strange problem with a if-statement: > > if ( $variabel_1 == $variabel_2 ) { > > }else{ > > } > > Sometimes when the variables are (exactly) equal, the > if-statement says > the opposite. The variables are of the same type (double) and have the > same numbers of decimals. comparing doubles is always tricky - suppose you have two doubles which have a value of 2.00 when printed using some sort of 'printf' function. In this case the variables might still be different, since one of them might be 1.99999999999 while the other is 2.0000000001. Also, the way doubles are encoded (IEEE format) allows for ambiguity, since there are some unused bits - this will also result in two doubles having the same value but not comparing as equal. The only sure-fire way to "compare" two doubles (or floats) is using a formula of the sort abs( ( a - b ) / ( a + b ) ) < epsilon where epsilon is some small number (e.g. 1E-9). Most books on numerical algorithms will tell you more about this. However, you *can* compare doubles to 0.0000 in most cases, since the bit pattern for 0.0000 is hardcoded (all zeros) HTH, JJ

« previous php.dev (#11739) next »