Visual studio 2008 unit test continues to fail

I created a method that calculates the harmonic mean value based on a doubling list. But when I run the test, it continues to fail, even if the output is the same.

My harmonic method:

public static double GetHarmonicMean(List<double> parameters) { var cumReciprocal = 0.0d; var countN = parameters.Count; foreach( var param in parameters) { cumReciprocal += 1.0d/param; } return 1.0d/(cumReciprocal/countN); } 

My testing method:

 [TestMethod()] public void GetHarmonicMeanTest() { var parameters = new List<double> { 1.5d, 2.3d, 2.9d, 1.9d, 5.6d }; const double expected = 2.32432293165495; var actual = OwnFunctions.GetHarmonicMean(parameters); Assert.AreEqual(expected, actual); } 

After starting the test, the following message appears:

Error Assert.AreEqual. Expected: <2.32432293165495>. In fact: <2,32432293165495>.

For me, these are the same meanings.

Can someone explain this? Or am I doing something wrong?

+4
source share
3 answers

Double overload for Assert.AreEqual accepts the "delta" parameter to allow duplication inaccuracies. You must specify a small value for this parameter.

+7
source

It is very difficult to convince the GetHarmonicMean method to accurately return 2.32432293165495. Double is much more accurate than 14 decimal places. Your result may be, for example:

2.32432293165495 - your_result = 0.0000000000000000012345 ... is definitely not zero.

+1
source

Double values ​​are rounded when they are displayed, so that they display several digits that are less than their capacity limit (to avoid rounding errors). Although the values ​​look the same, they actually have no exact meaning.

You can calculate the value and then display it in a two-way travel format:

 value.ToString("r") 

When a text representation created in this way is parsed, it ensures that the same double value that created it is received. You can put this in code and it will give you an exact match.

However, as a rule, double values ​​should not be compared for exact equality, since you rarely have a situation where you want to get an exact match. Also, testing for exact match may not be what you really want in this situation, as it depends on the fact that the implementation remains exactly the same. If you used a different algorithm, this would give different rounding errors, giving a slightly different result.

+1
source

Source: https://habr.com/ru/post/1307778/


All Articles