Double.NaN Equality in MS Test

Why am I getting this result?

[TestMethod] public void nan_test() { Assert.AreEqual(1, double.NaN, 1E-1); <-- Passes Assert.AreEqual(1, double.NaN); <-- Fails } 

What difference does the delta have in stating that NaN is equal to a number? Of course, it should always return false. I know IsNaN, but it is not useful here (see below).

Reference Information. I have a function that returns NaN (wrong), it should be a real number, but the test still passed. I use delta because it is a double equality of accuracy, the original test uses 1E-9.

+6
c # nan mstest
source share
3 answers

When you use Assert.AreEqual(1, double.NaN) , it tries the equality test on numbers and, of course, fails, because double.NaN not equal to anything.

When you execute Assert.AreEqual(1, double.NaN, 1E-1) , it should do arithmetic by numbers. In particular, it calculates

 Math.Abs((double) (expected - actual)) > delta Math.Abs(1 - double.NaN) > 1E-1 Math.Abs(double.NaN) > 1E-1 // All arithmetic with double.NaN returns double.NaN double.NaN > 1E-1 // All comparisons with double.NaN return false (except !=) 

which is false. It looks like the actual delta is no bigger than the delta you passed in, but only because it is trying to indicate that you cannot perform the comparison.

The moral of the story: NaN's behavior is pretty crazy (but the best smart people can come up with). Do your best to check NaN before performing any calculations in which you cannot miss the error, as shown below.

+3
source share

Could you use this test for NaN?

 double.IsNaN(somenNumber) 
+1
source share

Look here: Why is Assert.AreEqual (1.0, double.NaN, 1.0) passed?

Edit:

There is a specific error in Assert.AreEqual . in VS 2008 Microsoft.VisualStudio.QualityTools.UnitTestFramework it is encoded as

 if (Math.Abs((double) (expected - actual)) > delta) { // report error } 

As in your case, Math.Abs((double) (expected - actual)) is double.NaN , the comparison gives false double.NaN

+1
source share

All Articles