How to correctly and standardly compare floats?

From The Floating-Point Guide:

This is a bad way to do it because a
fixed epsilon chosen because it “looks
small” could actually be way too large
when the numbers being compared are
very small as well. The comparison
would return “true” for numbers that
are quite different. And when the
numbers are very large, the epsilon
could end up being smaller than the
smallest rounding error, so that the
comparison always returns “false”.

The problem with the “magic number” here is not that it’s hardcoded but that it’s “magic”: you didn’t really have a reason for choosing 0.000001 over 0.000005 or 0.0000000000001, did you? Note that float can approximately represent the latter and still smaller values – it’s just about 7 decimals of precision after the first nonzero digit!

If you’re going to use a fixed epsilon, you should really choose it according to the requirements of the particular piece of code where you use it. The alternative is to use a relative error margin (see link at the top for details) or, even better, or compare the floats as integers.

Leave a Comment