Comment by mtklein
1 day ago
My preferred way to compare floats as being interchangeably equivalent in unit tests is
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.
No comments yet
Contribute on Hacker News ↗