static T epsilon();
|
(C++11 前) | |
static constexpr T epsilon();
|
(C++11 起) | |
返回机器 epsilon ,即 1.0 与浮点类型 T
的下个可表示值的差。它仅若 std::numeric_limits<T>::is_integer == false 才有意义。
目录 |
T
|
std::numeric_limits<T>::epsilon() |
/* non-specialized */ | T();
|
bool | false |
char | 0 |
signed char | 0 |
unsigned char | 0 |
wchar_t | 0 |
char16_t | 0 |
char32_t | 0 |
short | 0 |
unsigned short | 0 |
int | 0 |
unsigned int | 0 |
long | 0 |
unsigned long | 0 |
long long | 0 |
unsigned long long | 0 |
float | FLT_EPSILON |
double | DBL_EPSILON |
long double | LDBL_EPSILON |
(无) | (C++11 前) |
noexcept 规定:
noexcept
|
(C++11 起) |
演示用机器 epsilon 比较浮点值相等
#include <cmath> #include <limits> #include <iomanip> #include <iostream> #include <type_traits> #include <algorithm> template<class T> typename std::enable_if<!std::numeric_limits<T>::is_integer, bool>::type almost_equal(T x, T y, int ulp) { // 机器 epsilon 必须被放大到所用值的绝对值 // 并乘以所需精度的 ULP (最后位置单位)倍数 return std::abs(x-y) < std::numeric_limits<T>::epsilon() * std::abs(x+y) * ulp // 除非结果为非正规 || std::abs(x-y) < std::numeric_limits<T>::min(); } int main() { double d1 = 0.2; double d2 = 1 / std::sqrt(5) / std::sqrt(5); if(d1 == d2) std::cout << "d1 == d2\n"; else std::cout << "d1 != d2\n"; if(almost_equal(d1, d2, 2)) std::cout << "d1 almost equals d2\n"; else std::cout << "d1 does not almost equal d2\n"; }
输出:
d1 != d2 d1 almost equals d2
(C++11)
(C++11) |
向给定值的下个可表示浮点值 (函数) |