Software & Finance





C++ FAQ - How accurate floating point comparison is?





Floating points are stored as in powers of 2 as per IEEE format. Please refer to Floating Point Indexing for more information on this.

 

This representation makes it difficult when we convert the floating point numbers into string or decimal and also when we compare two floating point numbers.

 

I have given here a very simple example. The difference between 7.52 and 7.59 is 0.07. But if you write a program to compare the difference against 0.07, you will not get the correct answer. This is a common known problem with floating point numbers.

 

There are couple of work around to this problem even there is no proper solution available. One solution would be having 6 digit accuracy (0.000001) and compare with > and < by subtracting and adding the delta to find out the numbers are equal or not.


Look at the sample code given below:

 


Source Code


#include <stdio.h>

#include <iostream>

#include <tchar.h>

 

void main()

{

    float a = 7.59;

    float b = 7.52;

    float d = 0.07;

    float m = a - b;

 

    std::cout << "m = " << m << "\n";

    std::cout << "d = " << d << "\n";

   

    if(m == d)

    {

        std::cout << "m = a - b\n";

    }

    else

    {

        std::cout << "m != a - b\n";

    }

 

    // Have 6 decimal point accuracy

    const float delta = 0.000001;

    if(m > d - delta &&

        m < d + delta)

    {

        std::cout << "Both m and d are equal";

    }

}

Output


 

m = 0.0700002

d = 0.07

m != a - b

Both m and d are equal