首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::numeric_limits::epsilon

static T epsilon();

?

(until C++11)

static constexpr T epsilon();

?

(since 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

例外

(none)

(until C++11)

noexcept specification: noexcept

(since C++11)

演示如何使用机器epsilon比较浮点值是否相等。

二次

代码语言:javascript
复制
#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)
{
    // the machine epsilon has to be scaled to the magnitude of the values used
    // and multiplied by the desired precision in ULPs (units in the last place)
    return std::abs(x-y) < std::numeric_limits<T>::epsilon() * std::abs(x+y) * ulp
    // unless the result is subnormal
           || 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";
}

二次

产出:

二次

代码语言:javascript
复制
d1 != d2
d1 almost equals d2

二次

另见

nextafternexttoward (C++11)(C++11)

next representable floating point value towards the given value (function)

代码语言:txt
复制
 ? cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com