Quote:Original post by Daniel Miller
If you shouldn't use == or !=, then wouldn't > and < be messed up as well?
Yes, but the effect is usually less significant.
e.g.
This may return false:
11.1f / 11.1f == 8.0f / 8.0f
And this could return true:
11.1f / 11.1f < 8.0f / 8.0f
The difference is that there's only 1 value out of 2^32 that make the first one true, however in the second case there's roughly 2^31 values that make it true. So if you're off by 1 bit for ==, it may never return true, whereas if you're off by 1 bit for <, it'll fix itself next iteration. You can have stability problems though if the calculation "lands" on the threshold and thus cause it to iterate true/false/true/true/false/true instead of a clean false/false/false/true/true/true.
Compares on float ought to be "fuzzy" and anything that's within the eplison should be considered equal.
struct scalar { typedef float float_t; scalar() {} explicit scalar(float_t f) : f(f) {} float_t f; //... }; inline bool operator==(scalar a, scalar b) { return abs(b-a).f < std::numeric_limits<scalar::float_t>::epsilon(); } inline bool operator!=(scalar a, scalar b) { return !(a==b); } inline bool operator<(scalar a, scalar b) { return (a.f<b.f) && (a!=b); }
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara