3

In this link, there is a function to check equality of 2 float point values:

template<class T>
typename std::enable_if<!std::numeric_limits<T>::is_integer, bool>::type
    almost_equal(T x, T y, int ulp)
{
    // the machine epsilon has to be scaled to the magnitude of the values used
    // and multiplied by the desired precision in ULPs (units in the last place)
    return std::abs(x-y) <= std::numeric_limits<T>::epsilon() * std::abs(x+y) * ulp
        // unless the result is subnormal
        || std::abs(x-y) < std::numeric_limits<T>::min();
}

But I am not quite get when will std::abs(x-y) < std::numeric_limits<T>::min() actually happen? any examples? Thanks.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
Baiyan Huang
  • 6,463
  • 8
  • 45
  • 72

1 Answers1

3

std::numeric_limits<T>::min() returns the smallest "normal" floating point value that can be represented. IEEE754 can represent values between 0 and std::numeric_limits<T>::min() as "subnormal" numbers. Take a look at this question which has several answers explaining this.

You can easily generate a subnormal value:

// Example program
#include <iostream>
#include <limits>
#include <cmath>

int main()
{
    std::cout << "double min: " << std::numeric_limits<double>::min() << " subnormal min: ";
    std::cout << std::numeric_limits<double>::denorm_min() << '\n';
    double superSmall = std::numeric_limits<double>::min();
    std::cout << std::boolalpha << "superSmall is normal: " << std::isnormal(superSmall)  << '\n';
    double evenSmaller = superSmall/2.0;
    std::cout << "evenSmaller = " << evenSmaller << '\n';
    std::cout << std::boolalpha << "evenSmaller is normal: " << std::isnormal(evenSmaller);

    std::cout << std::boolalpha << "std::abs(superSmall - evenSmaller) < std::numeric_limits<double>::min(): " << (std::abs(superSmall - evenSmaller) < std::numeric_limits<double>::min());
}

Which generates the following on my machine:

double min: 2.22507e-308 subnormal min: 4.94066e-324
superSmall is normal: true
evenSmaller = 1.11254e-308
evenSmaller is normal: false 
std::abs(superSmall - evenSmaller) < std::numeric_limits<double>::min(): true 
zdan
  • 28,667
  • 7
  • 60
  • 71