在采用C++编写算法时,经常需要判断两个浮点数是否相等。由于计算精度的原因,采用“==”运算符是不可行的。下面给出采用C++11标准判断两个浮点数是否相等的代码:
// Test whether two float or double numbers are equal.
// ulp: units in the last place.
template <typename T>
typename std::enable_if<!std::numeric_limits<T>::is_integer, bool>::type
IsAlmostEqual(T x, T y, int ulp = 2) {
// 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::fabs(x - y) <
std::numeric_limits<T>::epsilon() * std::fabs(x + y) * ulp
// unless the result is subnormal
|| std::fabs(x - y) < std::numeric_limits<T>::min();
}
上述代码中,std::enable_if<!std::numeric_limits<T>::is_integer, bool>::type
的含义是:如果数据类型T
不是整数类型,则返回值类型为bool
,否则会导致编译错误。也就是说,只允许进行非整数数值类型的比较。当然这里有个隐含前提,T
必须是数值类型,不可能拿一个类似于Person
的类型去实例化该函数,如果这样做,则std::numeric_limits<T>
肯定通不过,会报编译错误。
下面是示例代码:
#include <cmath>
#include <limits>
#include <iostream>
#include <type_traits>
// Test whether two float or double numbers are equal.
// ulp: units in the last place.
template <typename T>
typename std::enable_if<!std::numeric_limits<T>::is_integer, bool>::type
IsAlmostEqual(T x, T y, int ulp = 2)
{
// 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::fabs(x - y) < std::numeric_limits<T>::epsilon() * std::fabs(x + y) * ulp
// unless the result is subnormal
|| 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 << "d1 = " << d1 << std::endl;
std::cout << "d2 = " << d2 << std::endl;
if (d1 == d2)
{
std::cout << "d1 == d2" << std::endl;
}
else
{
std::cout << "d1 != d2" << std::endl;
}
if (IsAlmostEqual(d1, d2))
{
std::cout << "d1 almost equals d2" << std::endl;
}
else
{
std::cout << "d1 does not almost equal d2" << std::endl;
}
return 0;
}
- 1
Linux系统下,采用GCC编译器的编译命令为:
g++ -g -Wall -std=c++11 *.cpp -o test
输出结果如下:
d1 = 0.2
d2 = 0.2
d1 != d2
d1 almost equals d2