Bruce Dawson’s update on comparing floating point numbers.

Posted on 2012/02/26 by


Bruce Dawson wrote a very popular white paper on comparing floating point numbers. A few days ago, he posted an update with corrections and a great, easy-to-follow discussion of the topic. The problem addressed is determination when two floating point numbers are effectively equal. As you may have experienced, the “==” or “!=” operators are not reliable.

A very short synopsis of the article is “floating point math is hard”. However, his recent series of articles are excellent, and they help you to know what you are doing so the problems can be mitigated or at least understood.

A short synopsis is that in C/C++, you can use a union to perform type-punning to represent the float as an int. The difference in two integer representations gives the number of floating point representations between the two values. This is, as opposed to a tolerance independent of magnitude of the values, a good way to judge if two floats are almost equal. Caveats are that the sign of the values should be checked, and this will not work well for values around zero.

Also worth investigation is the boost documentation for calculating ULPS and the floating point comparison code in googletest. For what its worth, here’s what I put together for ITK based on Bruce’s article.

Posted in: General Interest