Tuesday, August 25, 2009

Comparing real numbers with = = and ! =

All computers use a limited amount of bits (0 and 1) to represent real numbers (and integers). This causes that in many cases there is a round off error in the results of calculations. the exact value might need more significant numbers than can be represented. In many cases it may not be possible because of the way real numbers are represented in the base of two. There are always round off errors and the result is only an approximate value. Fro example, the result of an expression 20.1 - 20.0 - 0.1 is not necessarily exactly 0.0 but instead because of round off errors 0.0(...lots of zeros...)1415926

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!"
        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 )

Previous post

Next post

No comments:

Post a Comment