转载自: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 "; else std::cout << "d1 != d2 "; if(almost_equal(d1, d2, 2)) std::cout << "d1 almost equals d2 "; else std::cout << "d1 does not almost equal d2 "; }
Output:
d1 != d2
d1 almost equals d2