采用C++ 11标准判断两个浮点数是否相等

采用C++ 11标准判断两个浮点数是否相等

在采用C++编写算法时,经常需要判断两个浮点数是否相等。由于计算精度的原因,采用“==”运算符是不可行的。下面给出采用C++11标准判断两个浮点数是否相等的代码:

// Test whether two float or double numbers are equal.

// ulp: units in the last place.

template

typename std::enable_if::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::epsilon() * std::fabs(x + y) * ulp

// unless the result is subnormal

|| std::fabs(x - y) < std::numeric_limits::min();

}

上述代码中,std::enable_if::is_integer, bool>::type的含义是:如果数据类型T不是整数类型,则返回值类型为bool,否则会导致编译错误。也就是说,只允许进行非整数数值类型的比较。当然这里有个隐含前提,T必须是数值类型,不可能拿一个类似于Person的类型去实例化该函数,如果这样做,则std::numeric_limits肯定通不过,会报编译错误。下面是示例代码:

#include

#include

#include

#include

// Test whether two float or double numbers are equal.

// ulp: units in the last place.

template

typename std::enable_if::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::epsilon() * std::fabs(x + y) * ulp

// unless the result is subnormal

|| std::fabs(x - y) < std::numeric_limits::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

相关推荐

怎么进入QQ农场?农场新手教程详解
365体育投注怎么玩

怎么进入QQ农场?农场新手教程详解

📅 09-08 👁️ 1725
吴思:李锐先生为什么能够存在
365体育投注怎么玩

吴思:李锐先生为什么能够存在

📅 01-22 👁️ 1367
饰品店的收入分析:一年究竟能赚多少?
365bet提现多久到账

饰品店的收入分析:一年究竟能赚多少?

📅 12-21 👁️ 6454