"A little progress everyday adds up to big results"

Saturday 30 June 2012

Comparing floating point numbers in programming languages

                    Some times, while programming, we might need to handle floating point numbers. In such cases, we cannot compare them simply by giving '==' operator, because, we cannot expect the numbers to be perfectly equal, if the number of values beyond the decimal point goes unlimited. In such cases, we can follow these steps.

(Assuming we need the floating point numbers to be equal for 4 digit precision)
For C/C++:
#define PRECISION_DIGITS 4
#define DELTA pow(10, - PRECISION_DIGITS)

For Java:
final int PRECISION_DIGITS = 4;
final float DELTA = Math.pow(10, - PRECISION_DIGITS);

and in the program, you can compare like this
if ( abs ( value1 - value 2 ) < DELTA ) // For Java change abs to Math.abs
{
       // Statements for value1 == value2
}
else
{
      // Statements for value1 != value2
}

More references regarding the floating point comparison is available in this site.

No comments:

Post a Comment