Tuesday, 22 January 2013

Comapring floating-points

Seems straight-forward... "Use delta!"

But today I tried explain it to my fiend, and... it wasn't that easy for me. So as title of my blog says "if you can't explain it simply you don't understand it well enough" - it was time to use google :)

And here it comes: http://randomascii.wordpress.com/2012/06/26/doubles-are-not-floats-so-dont-compare-them/ - I really recommend reading it, even as a Senior Developer you can be surprised by some things (I was).

Some sample to encourage you - yes, it's worth your damn precious time:

   float x = 1.1;
   if (x != 1.1)
      printf(“OMG! Floats suck!\n”);

On a fairly regular basis somebody will write code like this and then be shocked that the message is printed. Then somebody inevitably points them to my article and tells them to use an epsilon, and whenever that happens another angel loses their wings.

As mentioned in above article choosing the right epsilon the key. Here is nicely explained how to how to make  that choice.

And lastly, link provided by Tomek - a lot of reading ;)


  1. The most exhaustive explanation: http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

  2. Thanks Tomek, I think I've seen it some time ago, but it will be good to read it fully. Anyway the TDD book that you recommended (growing OO...) is really good and I think that some of approaches used by authors can be migrated to my daily-work :) Anyway I'm still around 140 page, so I'll be able to say something more after finishing it.