0

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?

user3358762
  • 3
  • 1
  • 1
  • 2
    Try this `cout << a << "-" << b << " = " << (a-b) << endl;` and see what you get. – Sergey Kalinichenko Mar 24 '14 at 18:58
  • 1
    Seriously, this has been addressed literally hundreds, if not thousands of times here. Just for a change of pace: http://www.parashift.com/c++-faq/floating-point-arith.html – PaulMcKenzie Mar 24 '14 at 18:58
  • 1
    Ahh, that must be it. I get "0.5 - 0.5 = 2.22045e-016" – user3358762 Mar 24 '14 at 19:02
  • @user3358762: Note that 0.5 does yield an exact representation in binary digits (0.1 in binary). So in your example, you must have computed a and b to be 0.5, but instead got an approximation. Is that a correct assumption? – PaulMcKenzie Mar 24 '14 at 19:10
  • Yes, a was calculated and could be an approximation while b was set to .5; Thanks for the info! – user3358762 Mar 24 '14 at 19:12

1 Answers1

2

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()

Community
  • 1
  • 1
Syntactic Fructose
  • 18,936
  • 23
  • 91
  • 177
  • 1
    absolute is fine but relative comparison rocks too : e.g : `abs(a - b) <= (atol + rtol * abs(b))` – Kiwi Mar 24 '14 at 19:03
  • 1
    @Kiwi there are a **lot** of possible solutions to this question, you're right. I just picked one that looked simple to understand – Syntactic Fructose Mar 24 '14 at 19:04