Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

This is the documentation for an old version of Boost. Click here to view this page for the latest version.
PrevUpHomeNext

BOOST_<level>_CLOSE

BOOST_WARN_CLOSE(left, right, tolerance);
BOOST_CHECK_CLOSE(left, right, tolerance);
BOOST_REQUIRE_CLOSE(left, right, tolerance);

These tools are used to check on closeness using strong relationship defined by the predicate

check_is_close( left, right, tolerance )

To check for the weak relationship use BOOST_<level>_PREDICATE family of tools with explicit check_is_close invocation.

The first parameter is the left compared value. The second parameter is the right compared value. Last third parameter defines the tolerance for the comparison in percentage units.

[Note] Note

It is required for left and right parameters to be of the same floating point type. You will need to explicitly resolve any type mismatch to select which type to use for comparison.

[Note] Note

Note that to use these tools you need to include additional header floating_point_comparison.hpp.

Example: BOOST_<level>_CLOSE usage with small values

Code

#define BOOST_TEST_MODULE example
#include <boost/test/included/unit_test.hpp>
#include <boost/test/floating_point_comparison.hpp>

BOOST_AUTO_TEST_CASE( test )
{
  double v1 = 1.23456e-10;
  double v2 = 1.23457e-10;

  BOOST_CHECK_CLOSE( v1, v2, 0.0001 );
  // Absolute value of difference between these two values is 1e-15. They seems 
  // to be very close. But we want to checks that these values differ no more then 0.0001%
  // of their value. And this test will fail at tolerance supplied.
}

Output

> example
Running 1 test case...
test.cpp(12): error in "test": difference between v1{1.23456e-010} and v2{1.23457e-010} exceeds 0.0001%

*** 1 failures is detected in test suite "example"
Example: BOOST_<level>_CLOSE usage with big values

Code

#define BOOST_TEST_MODULE example
#include <boost/test/included/unit_test.hpp>
#include <boost/test/floating_point_comparison.hpp>

BOOST_AUTO_TEST_CASE( test )
{
  double v1 = 1.23456e28;
  double v2 = 1.23457e28;

  BOOST_REQUIRE_CLOSE( v1, v2, 0.001 );
  // Absolute value of difference between these two values is 1e+23.
  // But we are interested only that it does not exeed 0.001% of a values compared
  // And this test will pass.
}

Output

> example
Running 1 test case...

*** No errors detected

See also:


PrevUpHomeNext