bool equiv(float x, float y) {
return (x <= y && y <= x)
|| (x != x && y != y);
}
This handles things like ±0 and NaNs (while NaNs can't be IEEE-754-equal per se, they're almost always interchangeable), and convinces -Wfloat-equal you kinda know what you're doing. Also everything visually lines up real neat and tidy, which I find makes it easy to remember.Outside unit tests... I haven't really encountered many places where float equality is actually what I want to test. It's usually some < or <= condition instead.
LegionMammal978•8h ago
Of course, inequalities show up in a lot more places, but are similarly fraught with difficulty, since mathematical statements may fail to translate to floating-point inequalities. E.g., in computational geometry, people have written entire papers about optimizing correct orientation predicates [0], since the naive method can easily break at small angles. This sort of thing is what often shows up as tiny seams in 3D video-game geometry.
[0] https://www.cs.cmu.edu/~quake/robust.html