何时会出现:std::abs(x - y) < std::numeric_limits<double>::min()?

3
在这个链接中,有一个检查两个浮点数值是否相等的函数:
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();
}

但我不太明白什么时候会发生 std::abs(x-y) < std::numeric_limits<T>::min()?有没有示例?谢谢。

1个回答

3

std::numeric_limits<T>::min()返回可表示的最小“正常”浮点值。IEEE754可以将0到std::numeric_limits<T>::min()之间的值表示为“次正常”数。请看这个问题,其中有几个答案解释了这个问题。

您可以轻松生成一个次正常值:

// 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());
}

在我的机器上运行此代码会生成以下结果:

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 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接