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


Calculating the Representation Distance Between Two floating-point Values (ULP) float_distance

Function float_distance finds the number of gaps/bits/ULP between any two floating-point values. If the significands of floating-point numbers are viewed as integers, then their difference is the number of ULP/gaps/bits different.

#include <boost/math/special_functions/next.hpp>
namespace boost{ namespace math{

template <class FPT>
FPT float_distance(FPT a, FPT b);

}} // namespaces
Description - float_distance

Returns the distance between a and b: the result is always a signed integer value (stored in floating-point type FPT) representing the number of distinct representations between a and b.

Note that

The function float_distance is equivalent to calculating the number of ULP (Units in the Last Place) between a and b except that it returns a signed value indicating whether a > b or not.

If the distance is too great then it may not be able to be represented as an exact integer by type FPT, but in practice this is unlikely to be a issue.