std::numeric_limits<T>::epsilon
来自cppreference.com
< cpp | types | numeric limits
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) { // 因为 `epsilon()` 是浮点数在区间 [1, 2) 中的间隙大小(ULP,末位单位), // 所以我们可以将其放大到区间 [2^e, 2^{e+1}) 中的间隙大小, // 其中 `e` 为 `x` 和 `y` 的幂指数。 // 如果 `x` 和 `y` 的间隙大小不同(即它们有不同指数),就取较小值。 // 我估计取较大值也可以。 const T m = std::min(std::fabs(x), std::fabs(y)); // 非正规数值有固定的指数,即 `min_exponent - 1`。 const int exp = m < std::numeric_limits<T>::min() ? std::numeric_limits<T>::min_exponent - 1 : std::ilogb(m); // 如果 `x` 和 `y` 之间的差处于 `n` 个 ULP 之内,则认为它们相等。 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 等于 y (" << n << " 个 ulp 以内)" << '\n'; break; } }
输出:
x = 0x1.3333333333333p-2 y = 0x1.3333333333334p-2 x != y x 等于 y (1 个 ulp 以内)
参阅
(C++11)(C++11) (C++11)(C++11)(C++11)(C++11) |
趋向给定值的下个可表示浮点值 (函数) |