Relational operators == and != can sometimes work illogically. The program:
#include <iostream>
using namespace std;
int main( void )
{
double value1 = 20.1;
double value2 = 20.0;
double value3 = 0.1;
if( ( value1 - value2 - value3 ) == 0 )
{
cout << "Corrrect!"
}
else
{
cout << "Sorry, there was an error!"
}
}
prints "sorry, there was an error!" when executed.
In order to be able to live with this unfortunate feature instead of testing real numbers for equality we test for near equality. Two real numbers are equal if they are close enough to each other. Instead of writing a == b with real numbers we should write |a-b| < EPSILON where EPSILON is the maximum allowable difference, 1E-8 for instance. In C++ the comparison of reals a == b can be handled as follows:
//Define somewhere at the beginning of the
//program the maximum tolerance
const double EPSILON = 1E-8;
...
...
//When later in the program two reals are
//tested for equality:
abs( a-b )
No comments:
Post a Comment