We can not compare doubles directly using ==
so one of the recommended methods is to use a threshold epsilon in order to determine equality based on our precision standard as defined by the threshold.
What I have been noticing is that when having 2 doubles the check usually recommended in relevant posts is if Math.abs(a - b) < epsilon
which is the part that is confusing to me.
In my understanding the comparison of the diff should be taking into account the magnitude of the numbers and not using the direct diff.
Example:
Assuming the threshold is 0.000001
in the following cases where we try to establish equality with a
double a = 57.33;
double b = 57.32973229;
double c = 57.33000002;
b
would be rejected since 57.33 - 57.32973229 = 0.00026771 > 0.000001
but to me it sounds quite unreasonable given the fact that this is less than 0.0004 error (0.00026771/57.33
). This is even more obvious with larger and larger (or smaller and smaller) numbers.
c
would be accepted since 57.33000002 - 57.33 = 0.00000002 < 0.000001
It seems quite impractical unless in very specific situations to accept as equal only c
.
What am I missing/misunderstanding here?
Update:
So why isn't the recommended approach (a - b)/Max(a,b) < epsilon
instead?