http://msdn.microsoft.com/en-us/library/system.double.epsilon.aspx
If you create a custom algorithm that determines whether two floating-point numbers can be considered equal, you must use a value that is greater than the Epsilon constant to establish the acceptable absolute margin of difference for the two values to be considered equal. (Typically, that margin of difference is many times greater than Epsilon.)
So is this not really an epsilon that could be used for comparisons? I don't really understand the MSDN wording.
Can it be used as the epsilon in the examples here? - What is the most effective way for float and double comparison?
And finally this seems really important so I'd like to make sure I have a solid implementation for equality, greater than, less than, less than or equal to, and greater than or equal to.
I don't know what they were smoking when they wrote that. Double.Epsilon
is the smallest representable non-denormal floating point value that isn't 0. All you know is that, if there's a truncation error, it will always be larger than this value. Much larger.
The System.Double
type can represent values accurate to up to 15 digits. So a simple first order estimate if a double value x
is equal to some constant is to use an epsilon of constant * 1E-15
public static bool AboutEqual(double x, double y) {
double epsilon = Math.Max(Math.Abs(x), Math.Abs(y)) * 1E-15;
return Math.Abs(x - y) <= epsilon;
}
You have to watch out though, truncation errors can accumulate. If both x
and y
are computed values then you have to increase the epsilon.