Robust epsilons in Floating Point

Michael Herf
April 5, 2000

I see people doing epsilon tests all the time by adding a constant:

#define EPSILON 0.000001
#define CLOSE(x, y)		(fabs(x - y) < EPSILON)
or something along those lines. Well, if you think about floating point for awhile, you'll realize that this isn't a good solution. Why? Because floating point isn't exact. The difference above could easily evaluate to zero; basically, you can't pick one epsilon for the whole range of floating point numbers.

But there's a very simple solution. Do the work on the integer side!

Here's the solution just for the single-precision case.

#define EPSILON 2
#define CLOSE(x, y)		(abs((unsigned&)x - (unsigned&)y) < EPSILON)
Similarly, you can do a bias:

#define EPSILON 2
#define BIAS(x)			((float&)((unsigned&)x + EPSILON))
And, for your reference, on MSVC, don't implement your own fabs or abs EVER. They're intrinsics, they compile to one assembly instruction without a branch, and so that's a bad idea.