Reputation: 6616
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?
Upvotes: 0
Views: 1335
Reputation: 308520
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.
Upvotes: 6