views:

120

answers:

3

I was doing some unit testing at work and a peculiar error popped up for one of the assertions. Note that expectedValue and actualValue are both doubles.

Assert.AreEqual(expectedValue, actualValue);

The exception stated that they were not equal, elaborating that "expected value: <6.8> actual value: <6.8>."

The expected value is a hard coded 6.8 and the actual value is formulated using database values going through our classification methods (such as Equal Records, or Jenks Natural Breaks).

My guess is that the difference is probably that the mantissas of the 2 values are similar up until the least significant bit. I updated the tests to include an epsilon to find if the two values are close enough, but I'm curious to if there is a way to force the mantissa to match with the display value of if I displayed that double. Does such a mantissa correction exist?

+1  A: 

I'm not entirely sure what you mean by forcing the mantissa to match the display value... there are no double values which are exactly 0.1, for example.

If you want some code to display the exact value of a double, however, I have a DoubleConverter.cs file which makes it easy:

 double d = 0.1;
 string x = DoubleConverter.ToExactString(d);

Another alternative is to use the round-trip format specifier ("r") when converting a double to string - that guarantees that the result has enough information to reproduce the same exact value later. In other words, if x != y, then x.ToString("r") != y.ToString("r").

Jon Skeet
I mean that I had 2 different values that both displayed in Visual Studio as 6.8, but their exact representation were different. How would I figure out which one is more correct (if that's even possible) and have them both be represented that way so an equality check would come out true?
Corey Ogburn
A: 

http://stackoverflow.com/questions/1594985/why-do-simple-math-operations-on-floating-point-return-unexpected-inacurate-res

bugtussle
a) the OP already understands that, b) just-a-link answers aren't very helpful, c) it should have been a comment
Henk Holterman
A: 

If you want to test whether the default display values match, just compare the default display values:

Assert.AreEqual(expectedValue.ToString(), actualValue.ToString());
Stephen Cleary