採用C++ 11標準判斷兩個浮點數是否相等

在採用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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章