Code Smell 108 - Float Assertions

Code Smell 108 - Float Assertions

Asserting two float numbers are the same is a very difficult problem

Maxi Contieri
·Dec 3, 2021·

1 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • Problems
  • Solutions
  • Context
  • Sample Code
  • Detection
  • Tags
  • Conclusion
  • Relations
  • More Info
  • Credits

TL;DR: Don't compare floats

Problems

  • Wrong test results

  • Fragile tests

  • Fail fast principle violation

Solutions

  1. Avoid floats unless you have REAL performance concerns

  2. Use arbitrary precision numbers

  3. If you need to compare floats compare with tolerance.

Context

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.

Sample Code

Wrong

Assert.assertEquals(0.0012f, 0.0012f); // Deprecated
Assert.assertTrue(0.0012f == 0.0012f); // Not JUnit - Smell

Right

Assert.assertEquals(0.0012f, 0.0014f, 0.0002); // true
Assert.assertEquals(0.0012f, 0.0014f, 0.0001); // false
// last parameter is the delta threshold

Assert.assertEquals(12 / 10000, 12 / 10000); // true
Assert.assertEquals(12 / 10000, 14 / 10000); // false

Detection

[X] Automatic

We can add a check con assertEquals() on our testing frameworks to avoid checking for floats.

Tags

  • Test Smells

Conclusion

We should always avoid comparing floats.

Relations

More Info

Credits

Photo by Mika Baumeister on Unsplash


God made the natural numbers; all else is the work of man.

Leopold Kronecker


This article is part of the CodeSmell Series.

 
Share this

Impressum

Technical Opinions are my own. I don't have the revealed truth.

Software Design is a creative activity. These are hints and not rigid rules.

I write on BackEnd Business Systems and OOP Design. My advice/experience might not suit other systems.

You can write me at info(at)maximilianocontieri.com