Search code examples
c++floating-pointprecisionfloating-accuracy

Comparing floating-point numbers (floats or doubles) for min/max


How to compare two different floats, to a certain degree of accuracy. I know that there are very slight imprecisions while using floats or doubles in any programming language, but which may however, be enough to cause this comparison of floats a < b to return a different value than it actually should.

I was solving a problem from the UVa Online Judge which gave me a Wrong Answer many times. It took few float values as input, albeit, to 2 decimal places. I figured out the makeshift solution, which was by splitting the input and converting it to ints, but I wouldn't prefer to use that always.

So my question is, what's the best way to compare whether a float a is lesser (or greater) than a float b, provided that the inputs of a and b are given correct to n decimal places, in this case, 2?

The language I prefer is C++.


Solution

  • Use std::numeric_limits<T>::epsilon() to check whether two numbers are almost equal. If you want to know whether one is greater/less you should also take into account the relative tolerance.

    #include <cmath>
    #include <limits>
    
    template < typename T >
    bool fuzzy_compare(T a, T b)
    {
      return std::abs(a - b) < std::numeric_limits<T>::epsilon();
    };