Comparing floating point values
.net, c#, comparison, floating-point
Solution
The following extension methods may be useful to implement Kevin's suggestion:
public static bool IsEqualTo(this double a, double b, double margin)
{
return Math.Abs(a - b) < margin;
}
public static bool IsEqualTo(this double a, double b)
{
return Math.Abs(a - b) < double.Epsilon;
}
So now you can just do:
if(x1.IsEqualTo(x2)) ...
if(x1.IsEqualTo(x2, 0.01)) ...
Just change the `IsEqualTo` to a more appropriate name, or change the default margin to anything better than `double.Epsilon`, if needed.
Problem
I just read a statement about the floating point value comparison Floating point values shall not be compared using either the == or != operators. Most floating point values have no exact binary representation and have a limited precision. If so what is the best method for comparing two floating point values?