#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.

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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

  1. oldWing says:

    Epsilon should be scaled relative to the input values:

    return Math.Abs(f1 – f2) Math.Abs(f2) ? f1 : f2 );

    Otherwise you run out of precision for large values and ignore the inputs for small values.

    • Darkhog says:

      Another way would be to use configurable epsilon, so you can adjust comparison precision on case-by-case basis (trial&error):
      bool nearlyEqual(float f1, float f2, float eps){
      // Equal if they are within 0.00001 of each other
      return Mathf.Abs(f1 – f2) < eps;
      }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: