#416 – Use an Epsilon to Compare Two Floating Point Numbers

Because of problems with the precision of floating point numbers, two numbers that would ought to be considered equal might actually have different values.  Because of this, you typically don’t want to use the == operator on floating point numbers, when checking for equality.  Instead, you likely want to see if the difference between the two numbers is small enough that the numbers can be considered equal.

Here’s helper function that determines if two float values are nearly equal.

        public static bool NearlyEqual(float f1, float f2)
        {
            // Equal if they are within 0.00001 of each other
            return Math.Abs(f1 - f2) < 0.00001;
        }

We then get the following results:

            float f1 = 1.0f / 6.0f;
            float f2 = (f1 * 6.0f) - 1.0f;   // Should be 0.0
            float f3 = 0.0f;

            bool check = (f2 == f3);       // false !
            check = NearlyEqual(f2, f3);   // true


The value that you choose for epsilon will typically depend on your application.