Floating point comparison functions for C#

Viewed 134948

Can someone point towards (or show) some good general floating point comparison functions in C# for comparing floating point values? I want to implement functions for IsEqual, IsGreater an IsLess. I also only really care about doubles not floats.

14 Answers

For people coming here for UNITY specific

There is Mathf.Approximately so writing

if(Mathf.Approximately(a, b))

basically equals writing

if(Mathf.Abs(a - b) <= Mathf.Epsilon)

where Mathf.Epsilon

The smallest value that a float can have different from zero.

static class FloatUtil {

    static bool IsEqual(float a, float b, float tolerance = 0.001f) {
      return Math.Abs(a - b) < tolerance;
    }

    static bool IsGreater(float a, float b) {
      return a > b;
    }

    static bool IsLess(float a, float b) {
      return a < b;
    }
}

The value of tolerance that is passed into IsEqual is something that the client could decide.

IsEqual(1.002, 1.001);          -->   False
IsEqual(1.002, 1.001, 0.01);    -->   True
if (Math.Abs(1.0 - 1.01) < TOLERANCE) {
//true
}

where TOLERANCE is the amount you wish to achieve. e.g. TOLERANCE = 0.01 will not result in true. But if you keep it 0.011 it will result in true since the diff is within reach.

Related