Question

I have two doubles, a and b, in C++ that should be equal but for some reason are not being treated as such. The following code:

cout << a << "==" << b << ": " << (a == b) << endl;

is outputting

0.5 == 0.5: 0

Any ideas why this is resolving to false?

Was it helpful?

Solution

To avoid errors when comparing decimals it might be useful to use a function:

bool AreSame(double a, double b)
{
    return fabs(a - b) < EPSILON;
}

where EPSILON could be represented by a small number such as .001

grabbed from this question.

EDIT: by including <limits> one could use std::numeric_limits<double>::epsilon()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top