Namespaces
Variants
Actions

Talk:cpp/types/numeric limits/epsilon

From cppreference.com

[edit] Bibliography for the implementation of almost_equal()

Hi,

Is there any bibliographic reference for the implementation of almost_equal(), in the example section? I wonder, in particular, how it compares to:

double divide_saturated(double a, double b) {
    // Check if division would overflow.
    if (b < 1.0 && (a > b * std::numeric_limits<double>::max())) {
        return std::numeric_limits<double>::max();
    }
 
    // Check if division would underflow (or is 0.0/something).
    if (a == 0.0 || (b > 1.0 && (a < b * std::numeric_limits<double>::min())))
        return 0.0;
 
    return a / b;
}
 
// This implementation is based on Knuth, The Art of Computer
// Programming, vol. 2, 4.2.2, equations (34) and (36).
//
// The naive implementation would be:
//
//   double const d = std::abs( a - b ) ;
//   return d <= epsilon * std::abs( a ) &&
//          d <= epsilon * std::abs( b ) ;
//
// however the multiplications on the right hand side may cause
// underflow. So we go for
//
//   d / abs( a ) <= epsilon &&
//   d / abs( b ) <= epsilon
//
// except that we check the division on the left hand side.
bool are_close_within_tolerance(double a, double b, double epsilon) {
    double const d = std::abs(a - b);
    return divide_saturated(d, std::abs(a)) <= epsilon &&
           divide_saturated(d, std::abs(b)) <= epsilon;
}

Thanks. --2001:B01:2404:4:0:0:0:56 08:12, 9 November 2018 (PST)

The example on this page could certainly use a review (since it appears people use it as more than just a demo of numeric_limits<>::epsilon()). As for your example, for one thing, it does not make use of that "epsilon". --Cubbi (talk) 11:32, 9 November 2018 (PST)
Of course, I didn't mean to provide an example for this page (because I'm not using epsilon()). I'm just after a general almost_equal() function for floating points, and wondered whether the one provided in this page is such a function. The code I provided is, as the comments say, based on Knuth. I wondered on which source or reasoning is almost_equal() based, instead. --2001:B01:2404:4:0:0:0:56 01:00, 12 November 2018 (PST)
I believe that the original implementation of almost_equal() was based on this answer on StackOverflow. Also check out this question on StackExchange for revelant infomation. --Raniarel (talk) 21:31, 18 October 2023 (PDT)