名前空間
変種
操作

std::numeric_limits<T>::epsilon

From cppreference.com
< cpp‎ | ‎ | 数値制限
 
 
ユーティリティライブラリ
言語サポート
型のサポート (基本型、RTTI)
ライブラリ機能検査マクロ (C++20)
プログラムユーティリティ
可変引数関数
コルーチンサポート (C++20)
契約サポート (C++26)
三方比較
(C++20)
(C++20)(C++20)(C++20)  
(C++20)(C++20)(C++20)

汎用ユーティリティ
関係演算子 (C++20で非推奨)
 
 
 
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)
与えられた値に向かって、次に表現可能な浮動小数点数値を求める
(関数) [編集]
English 日本語 中文(简体) 中文(繁體)