Asserting two float numbers are the same is a very difficult problem
TL;DR: Don't compare floats
-
Wrong test results
-
Fragile tests
-
Fail fast principle violation
-
Avoid floats unless you have REAL performance concerns
-
Use arbitrary precision numbers
-
If you need to compare floats compare with tolerance.
Comparing float numbers is an old computer science problem.
The usual solution is to use threshold comparisons.
We recommend avoiding floats at all and trying to use infinite precision numbers.
Assert.assertEquals(0.0012f, 0.0012f); // Deprecated
Assert.assertTrue(0.0012f == 0.0012f); // Not JUnit - Smell
Assert.assertEquals(0.0012f, 0.0014f, 0.0002); // true
Assert.assertEquals(0.0012f, 0.0014f, 0.0001); // false
// The last parameter is the delta threshold
Assert.assertEquals(12 / 10000, 12 / 10000); // true
Assert.assertEquals(12 / 10000, 14 / 10000); // false
[X] Automatic
We can add a check con assertEquals() on our testing frameworks to avoid checking for floats.
- Test Smells
We should always avoid comparing floats.
Code Smell 71 - Magic Floats Disguised as Decimals
Photo by Mika Baumeister on Unsplash
God made the natural numbers; all else is the work of man.
Leopold Kronecker
Software Engineering Great Quotes
This article is part of the CodeSmell Series.