std::numeric_limits<T>::epsilon
提供: cppreference.com
<tbody>
</tbody>
<tbody class="t-dcl-rev ">
</tbody><tbody>
</tbody>
static T epsilon() throw(); |
(C++11未満) | |
static constexpr T epsilon() noexcept; |
(C++11以上) | |
機械イプシロン、つまり、浮動小数点型 T によって表現可能な 1.0 の次の値と 1.0 との差を返します。 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
|
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 |
例
浮動小数点値を等しいか比較するために機械イプシロンの使用をデモンストレーションします。
Run this code
#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)
{
// 機械イプシロンは、使用される値の絶対値にスケールして
// ULP (unit in the last place) 単位の所望の精度を掛ける必要があります。
return std::fabs(x-y) <= std::numeric_limits<T>::epsilon() * std::fabs(x+y) * ulp
// ただし結果が非正規化数の場合は除く。
|| std::fabs(x-y) < std::numeric_limits<T>::min();
}
int main()
{
double d1 = 0.2;
double d2 = 1 / std::sqrt(5) / std::sqrt(5);
std::cout << std::fixed << std::setprecision(20)
<< "d1=" << d1 << "\nd2=" << d2 << '\n';
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=0.20000000000000001110
d2=0.19999999999999998335
d1 != d2
d1 almost equals d2
関連項目
(C++11)(C++11) (C++11)(C++11)(C++11)(C++11) |
指定された値に向かう方向の次の表現可能な浮動小数点値を返します (関数) |