Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing failing due to 0.000000001f inaccuarcy

A vector is out by 0.000000001f so the test is failing.

Doing the logic in my head yeilds -1.0f, -1.0f but when I wrote the code to pass the test (Using the built in Vector methods) the answer comes back as -0.999999999f, -0.999999999f which is still 'right'.

This is C# (Vector2 class provided by the XNA framework) by the way, so I tried adding an epsilon value to each the x and y parameter of the Vector but this didn't work.

The way I see it is that by coding the answer, I'm writing the production code. E.g. it would be the same. Surely this is not the right.

Any advice?

like image 837
Finglas Avatar asked Jan 23 '23 14:01

Finglas


2 Answers

Unit testing frameworks usually provide asserts for floats that take a precision. For example in Visual Studio Test you can write:

Assert.AreEqual(1.0f, 0.9999999999f, 1e-3); // passes
Assert.AreEqual(1.0f, 0.9f, 1e-3); // fails
like image 180
Darin Dimitrov Avatar answered Jan 26 '23 04:01

Darin Dimitrov


Please see my answer here.

It is not about C#, but the same logic applies.

like image 36
Brian R. Bondy Avatar answered Jan 26 '23 03:01

Brian R. Bondy