I've seen posts like:
What is the most effective way for float and double comparison?
And many other related posts.
I saw in d3js library, it uses the following comparison:
return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
Is it OK to use this in C/C++ to do the comparison of double and float?
6 Answers 6
is the following code sufficient?
No.
If not, why?
Because it's the same as == (at least for non-edge cases, that is.)
8 Comments
< combined with > will be ==?This is not sufficient because that will return true if either a or b is NaN
Comments
This is basically about the notion that using "nearly equal" can somehow make up for not knowing enough about floating-point calculations to get reliable results. "Nearly equal" is an advanced technique; it will often bite you because it is not transitive (that is, a "nearly equals" b and b "nearly equals" c does not mean that a "nearly equals" c). If you're a serious programmer, learn the basics of how floating-point works. Nobody's surprised that (1/2)*2) is not 1, but somehow people don't grasp that (1.0/10.0)*10.0 is also not 1 (unless your system has decimal floating point), and for exactly the same reason. That's a failure of education, but having been taught badly doesn't mean you can't learn it. (end of rant)
Comments
The idea of comparing with a tolerance is that two values that are almost exactly the same might want to be considered the same. If you have 2.000000000000 and 2.000000000001, should those be equal, or not? If they should be then your code will fail.
1 Comment
Your mistake is, you read the article which has
diff = A - B;
return (diff < EPSILON) && (-diff > EPSILON);
and, you put EPSILON = 0 and turn it into
if (!(a > b) && !(a < b))
You shouldn't suppose EPSILON as 0. Because you should consider a bit error is float/double comparison which we call it EPSILON.
Comments
You really need to read this document:
https://ece.uwaterloo.ca/~dwharder/NumericalAnalysis/02Numerics/Double/paper.pdf
It is Golberg's paper = whatever every programmer should know about floating point.
xor eax, eax:Pa == b.