Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is to round a correct way for making float-double comparison

With this question as base, it is well known that we should not apply equals comparison operation to decimal variables, due numeric erros (it is not bound to programming language):

bool CompareDoubles1 (double A, double B)
{
   return A == B;
}

The abouve code it is not right. My questions are:

  1. It is right to round to both numbers and then compare?
  2. It is more efficient?

For instance:

bool CompareDoubles1 (double A, double B)
    {
       double a = round(A,4);
       double b = round(B,4)
       return a == b;
    }

It is correct?

EDIT

I'm considering round is a method that take a double (number) and int (precition):

bool round (float number, int precision);

EDIT I consider that a better idea of what I mean with this question will be expressed with this compare method:

bool CompareDoubles1 (double A, double B, int precision)
        {
           //precition could be the error expected when rounding
           double a = round(A,precision);
           double b = round(B,precision)
           return a == b;
        }
like image 278
Raúl Otaño Avatar asked Aug 31 '25 17:08

Raúl Otaño


1 Answers

Usually, if you really have to compare floating values, you'd specify a tolerance:

bool CompareDoubles1 (double A, double B, double tolerance)
{
   return std::abs(A - B) < tolerance;
}

Choosing an appropriate tolerance will depend on the nature of the values and the calculations that produce them.

Rounding is not appropriate: two very close values, which you'd want to compare equal, might round in different directions and appear unequal. For example, when rounding to the nearest integer, 0.3 and 0.4 would compare equal, but 0.499999 and 0.500001 wouldn't.

like image 184
Mike Seymour Avatar answered Sep 02 '25 16:09

Mike Seymour