Possible Duplicate:
How should I do floating point comparison?
Is it not recommended to compare for equality a double and a double literal in C++, because I guess it is compiler dependent?
To be more precise it is not OK to compare a double which is hard-coded (a literal in the source code) and a double which should be computed, as the last number of the resultant of the calculation can vary from one compiler to another. Is this not standardized?
I heard this is mentioned in Knuth’s TeXbook, is that right?
If this is all true, what is the solution?
You’ve misunderstood the advice a bit. The point is that floating-point computations aren’t exact. Rounding errors occur, and precision is gradually lost. Take something as simple as
1.0/10.0. The result should be0.1, but it isn’t, because0.1cannot be represented exactly in floating-point format. So the actual result will be slightly different. The same is true for countless other operations, so the point has nothing to do with const doubles. It has to do with not expecting the result to be exact. If you perform some computation where the result should be1.0, then you should not test it for equality against1.0, because rounding errors might mean that it actually came out0.9999999997instead.So the usual solution is to test if the result is sufficiently close to
1.0. If it is close, then we assume “it’s good enough”, and act as if the result had been 1.0.The bottom line is that strict equality is rarely used for floating-point values. Instead, you should test if the difference between the two values is less than some small value (typically called the epsilon)