double compare 0.2 != 0.2 How?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Curtis Rutland
    Recognized Expert Specialist
    • Apr 2008
    • 3264

    #16
    Most of my work thus far hasn't had much to do with floating point precision, I'm sure I would have found some of that info if I was ever required to.

    Comment

    • vekipeki
      Recognized Expert New Member
      • Nov 2007
      • 229

      #17
      That is how things work, the only thing you can do is add a handy extension method to System.Double, something like:

      Code:
      public static bool AlmostEquals
           (this double a, double b)
      {
          return (Math.Abs(a - b) < 1e-5);
      }
      and then use it, when appropriate, like
      Code:
      MessageBox.Show((1.0 - 0.8).AlmostEquals(0.2));
      Although if this is only a unit test, you might just add a method to your test module.

      Comment

      • IanWright83
        New Member
        • Apr 2009
        • 9

        #18
        Originally posted by vekipeki
        That is how things work, the only thing you can do is add a handy extension method to System.Double, something like:

        Code:
        public static bool AlmostEquals
             (this double a, double b)
        {
            return (Math.Abs(a - b) < 1e-5);
        }
        and then use it, when appropriate, like
        Code:
        MessageBox.Show((1.0 - 0.8).AlmostEquals(0.2));
        Although if this is only a unit test, you might just add a method to your test module.
        Not sure off the top of my head, but is it possible to overload the double == operator in a similar approach using extension methods?

        Comment

        • vekipeki
          Recognized Expert New Member
          • Nov 2007
          • 229

          #19
          No, you cannot override the existing == operator (it is a static method). But I wouldn't call that a good idea even if it were possible, modifications like that would be a nightmare to debug.

          Comment

          Working...