An Elegant Way to Compare Float Values in C++

Compare Float Values

  • Note that this function is only meaningful if std::numeric_limits<T>::is_integer == false.
C++
#include <limits>

template<typename T>
bool IsFloatEqual(T f0, T f1)
{
    return abs(f0 - f1) < std::numeric_limits<T>::epsilon();
}

std::numeric_limits<T>::epsilon

  • According to cppreference.com, std::numeric_limits<T>::epsilon returns the machine epsilon, that is, the difference between 1.0 and the next value representable by the floating-point type T.
C++
#include <limits> // std::numeric_limits
#include <iostream>
#include <cstdlib>

int main(void)
{
    std::cout << "FLOAT\t" << std::numeric_limits<float>::epsilon() << std::endl;
    std::cout << "DOUBLE\t" << std::numeric_limits<double>::epsilon() << std::endl;
    std::cout << "INT\t\t" << std::numeric_limits<int>::epsilon() << std::endl;

    return EXIT_SUCCESS;
}
FLOAT1.19209e-007
DOUBLE2.22045e-016
INT0

Leave a Reply

Your email address will not be published. Required fields are marked *