0

I am trying to compare 2 doubles which fall in [0.0, 1.0].

My function (taken from https://stackoverflow.com/a/17341 )-

inline bool isEqual(double x, double y)
{
    const double epsilon = 0.000001;
    return fabs(x - y) < epsilon;
}

Usage-

cerr << isEqual(1.000001, 1.000002) << endl;
cerr << isEqual(1.000010, 1.000020) << endl;

The output is-

0
0

Whereas I am expecting first to be true, second to be false. Please tell me where I am going wrong and how to fix it?

Community
  • 1
  • 1
Vinayak Garg
  • 6,518
  • 10
  • 53
  • 80
  • 1
    You will always get rouding errors with floating-point. And even if it were exact precision, `fabs(1.000001 - 1.000002)` would be _equal_ to `0.000001`, not strictly less than it. – gx_ Jun 20 '13 at 15:50
  • The function has the wrong name. It does **not** test for equality, and should be called `nearly_equals` or something along that line. – Pete Becker Jun 20 '13 at 17:55

1 Answers1

6

1.000001 when limited to the usual 64-bit IEEE floating point representation is actually 1.0000009999999999177333620536956004798412. Likewise 1.000002 is actually 1.0000020000000000575113290324225090444087. The two are ever more slightly apart than 0.000001.

You can use a very slightly larger comparison value to catch this:

    const double epsilon = 0.0000011;

It really isn't possible to completely eliminate any rounding problems with floating point numbers.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • Thanks! That solved it. However I decided to solve problem with higher precision, and in end print answer with 5 digits of precision. – Vinayak Garg Jun 20 '13 at 16:54
  • Anyway, doesn't `epsilon = 0.000001` give you **six** digits of precision instead of five? – Massa Jun 20 '13 at 17:15