命名空间
变体
操作

std::numeric_limits<T>::epsilon

来自 cppreference.com
 
 
实用工具库
语言支持
类型支持 (基本类型,RTTI)
库功能测试宏 (C++20)
动态内存管理
程序实用工具
协程支持 (C++20)
可变参数函数
调试支持
(C++26)
三向比较
(C++20)
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
通用实用工具
日期和时间
函数对象
格式化库 (C++20)
(C++11)
关系运算符 (C++20 中已弃用)
整数比较函数
(C++20)(C++20)(C++20)   
(C++20)
交换类型操作
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
通用词汇类型
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)
基本字符串转换
(C++17)
(C++17)

 
 
 
static T epsilon() throw();
(直到 C++11)
static constexpr T epsilon() noexcept;
(自 C++11 起)

返回机器 epsilon,即 1.0 与浮点数类型 T 可表示的下一个值之间的差。它仅在 std::numeric_limits<T>::is_integer == false 时有意义。

[编辑] 返回值

T std::numeric_limits<T>::epsilon()
/* 非特化 */ T()
bool false
char 0
signed char 0
unsigned char 0
wchar_t 0
char8_t (自 C++20 起) 0
char16_t (自 C++11 起) 0
char32_t (自 C++11 起) 0
short 0
unsigned short 0
int 0
unsigned int 0
long 0
unsigned long 0
long long (自 C++11 起) 0
unsigned long long(自 C++11 起) 0
float FLT_EPSILON
double DBL_EPSILON
long double LDBL_EPSILON

[编辑] 示例

演示使用机器 epsilon 来比较浮点数的值以判断是否相等

#include <algorithm>
#include <cmath>
#include <cstddef>
#include <iomanip>
#include <iostream>
#include <limits>
#include <type_traits>
 
template <class T>
std::enable_if_t<not std::numeric_limits<T>::is_integer, bool>
equal_within_ulps(T x, T y, std::size_t n)
{
    // Since `epsilon()` is the gap size (ULP, unit in the last place)
    // of floating-point numbers in interval [1, 2), we can scale it to
    // the gap size in interval [2^e, 2^{e+1}), where `e` is the exponent
    // of `x` and `y`.
 
    // If `x` and `y` have different gap sizes (which means they have
    // different exponents), we take the smaller one. Taking the bigger
    // one is also reasonable, I guess.
    const T m = std::min(std::fabs(x), std::fabs(y));
 
    // Subnormal numbers have fixed exponent, which is `min_exponent - 1`.
    const int exp = m < std::numeric_limits<T>::min()
                  ? std::numeric_limits<T>::min_exponent - 1
                  : std::ilogb(m);
 
    // We consider `x` and `y` equal if the difference between them is
    // within `n` ULPs.
    return std::fabs(x - y) <= n * std::ldexp(std::numeric_limits<T>::epsilon(), exp);
}
 
int main()
{
    double x = 0.3;
    double y = 0.1 + 0.2;
    std::cout << std::hexfloat;
    std::cout << "x = " << x << '\n';
    std::cout << "y = " << y << '\n';
    std::cout << (x == y ? "x == y" : "x != y") << '\n';
    for (std::size_t n = 0; n <= 10; ++n)
        if (equal_within_ulps(x, y, n))
        {
            std::cout << "x equals y within " << n << " ulps" << '\n';
            break;
        }
}

输出

x = 0x1.3333333333333p-2
y = 0x1.3333333333334p-2
x != y
x equals y within 1 ulps

[编辑] 另请参见

(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)
下一个可表示的浮点数,朝给定值的方向
(函数) [编辑]