Re: How to overload == for System.Double

Peter Ritchie <[email protected]> Fri, 2 Feb 2007 21:36:59 -0500
Newsgroups gmane.comp.windows.devel.dotnet.cx
Message-ID <LISTSERV%[email protected]>
As Marc points out, the .NET Epsilon fields are not the same as epsilon
values found in other languages.

In C/C++ DBL_EPSILON is defined as 2.2204460492503131e-016; a far cry from
Double.Epsilon, which is declared as 4.94065645841247e-324 (or even
Single.Epsilon, which is declared as 1.4e-45).

It's common in C to define a macro (or a template function in C++ for type
safety) as follows:

#define DOUBLE_EQ(x,v) (((v - DBL_EPSILON) < x) && (x <( v + DBL_EPSILON)))

You could do the same thing in C#:

static class Helper
{
 private const Double DoubleEpsilon = 2.2204460492503131e-016;
 private const Double SingleEpsilon = 1.192092896e-07;
 public static bool Equal(Double l, Double r)
 {
  return (((r - DoubleEpsilon) < l) && (l <( r +
DoubleEpsilon)));
 }
 public static bool Equal(Single l, Single r)
 {
  return (((r - SingleEpsilon) < l) && (l <( r +
SingleEpsilon)));
 }
}

There is currently a Connect issue logged (way back in 2004) regarding
this Epsilon deviation:
https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?
FeedbackID=93726  Not surprising, this issue was closed without resolution.

Another issue was logged in 2004, about the missing ability to test for
near-equality of float-point values (in that the Epsilon fields can/should
not be used for that):
https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?
FeedbackID=93727 which seems to be ignored by Microsoft.

I can only image how many people have gone down the .NET Epsilon path only
to introduce bugs and have to stop using it; how often do you need to test
if a value is as close to zero as it can possibly be without being a zero?

===================================
This list is hosted by DevelopMentorĀ®  http://www.develop.com

View archives and manage your subscription(s) at http://discuss.develop.com