# V2550. MISRA. Floating-point values should not be tested for equality or inequality.

This diagnostic rule is based on the software development guidelines developed by MISRA (Motor Industry Software Reliability Association).

This rule applies only to C++. When comparing values of real types for equality or non-equality, the results may vary depending on the processor being used and compiler settings.

Example of non-compliant code:

    const double PI_div_2 = 1.0;
    const double sinValue = sin(M_PI / 2.0);

    if (sinValue == PI_div_2) { .... }

To compare values of real types correctly, either use the predefined constant 'std::numeric_limits<float>::epsilon()' or 'std::numeric_limits<double>::epsilon()' or create your own constant 'Epsilon' of custom precision.

Fixed code:

    const double PI_div_2 = 1.0;
    const double sinValue = sin(M_PI / 2.0);

    // equality
    if (fabs(a - b) <= std::numeric_limits<double>::epsilon()) { .... };

    // inequality
    if (fabs(a - b) > std::numeric_limits<double>::epsilon()) { .... };

In some cases, it is allowed to compare two real numbers using the '==' or '!=' operator, for example, when checking a variable for a known value:

    bool foo();
    double bar();

    double val = foo() ? bar() : 0.0;
    if (val == 0.0) { .... }

The analyzer does not issue the warning if a value is compared with itself. Such a comparison is useful to check a variable for NaN:

    bool isnan(double value) { return value != value; }

However, a better style is to implement this check through the 'std::isnan' function.

This diagnostic is classified as:

MISRA-CPP-2008-6.2.2