Michael D
Michael D

Reputation: 1479

floating point comparison in c++11

I am used to compare the floating point with the following function. However, I just check that c++11 provides some floating point comparison function like isgreaterequal. My question is whether I should replace it with the functions in the standard?

bool isEqual(double lhs, double rhs, double epsilon = /std::numeric_limits<double>::epsilon())
{
    if (lhs == rhs)
    {
        return true;
    }

    return fabs(lhs - rhs) <= ( (fabs(lhs) > fabs(rhs) ? fabs(rhs) : fabs(lhs)) * epsilon);
}

Upvotes: 1

Views: 2838

Answers (1)

Dylan Holmes
Dylan Holmes

Reputation: 782

According to: cplusplus.com

Using isgreaterequal, if either arguments are NaN, then the comparison is evaluates to false.

Using >=, if either arguments are NaN, then an FE_INVALID exception will be raised.

So, I think you should keep your function the way it is, as you probably would like to know if one of your arguments was NaN.

From C11 Draft N1570:
p.516 Section F.9.3 Relational operators

x < y → isless(x,y) (and similarly for ≤, >, ≥) Though numerically equal, these expressions are not equivalent because of side effects when x or y is a NaN and the state of the FENV_ACCESS pragma is ‘‘on’’. This transformation, which would be desirable if extra code were required to cause the ‘‘invalid’’ floating-point exception for unordered cases, could be performed provided the state of the FENV_ACCESS pragma is ‘‘off’’.

Upvotes: 1

Related Questions