std::numeric_limits::epsilon

转载自:https://tool.oschina.net/uploads/apidocs/cpp/en/cpp/types/numeric_limits/epsilon.html

#include <cmath>
#include <limits>
#include <iomanip>
#include <iostream>
#include <type_traits>
 
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 larger value
    // and multiplied by the desired precision in ULPs (units in the last place)
    return std::abs(x-y) <=   std::numeric_limits<T>::epsilon()
                            * std::max(std::abs(x), std::abs(y))
                            * ulp;
}
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";
}

Output:

d1 != d2
d1 almost equals d2

 

posted on 2021-01-27 15:44  dchao  阅读(697)  评论(0编辑  收藏  举报

导航