Skip to content

2.3 comparing floating point numbers

Jeff Trull edited this page May 15, 2013 · 2 revisions

Answer

Equality comparisons on floating point numbers are tricky. Use the Boost.Test predicates to perform a relative "closeness" check between two numbers to your desired tolerance:

#include <iostream>
#include <boost/test/floating_point_comparison.hpp>

int main() {
   using namespace boost::test_tools;

   float a = 1000.0, b = 1009.0;

   auto pcttol = percent_tolerance(1.0);    // within 1% of the comparison arguments

   std::cout << "a is " << (check_is_close(a, b, pcttol) ? "" : "NOT ")
             << "within 1% of b" << std::endl;
}

##Discussion Floating point arithmetic seems straightforward but is full of traps for the unwary. In particular, small rounding errors can accumulate in ways that are dependent on the sequence of operations and the input data. Those errors can then produce a number that is very very close - but not exactly equal - to the number you expected. As a result, the best practice for floating point equality comparisons is to choose a tolerance range, as tight as needed for your application, and assume that any two numbers within that distance of each other are the "same" for your purposes. As part of its unit testing predicates, the Boost.Test library provides carefully designed facilities for floating-point comparison - see the library documentation for more details.

Clone this wiki locally