Rule Definition
The inherent nature of floating-point types is such that comparisons of equality will often not evaluate to true, even when they are expected to. Also, the behavior of such a comparison cannot be predicted before execution, and may well vary from one implementation to another.
The recommended method for achieving deterministic floating-point comparisons is to write a library that implements the comparison operations. The library should take into account the floating-point granularity (std::numeric_limits:: epsilon()) and the magnitude of the numbers being compared.
Due to rounding errors, most floating-point numbers end up being slightly imprecise. As long as this imprecision stays small, it can usually be ignored. However, it also means that numbers expected to be equal (e.g. when calculating the same result through different correct methods) often differ slightly, and a simple equality test fails.
A comparison between a floating-point number and an integer has the same problem since the integer is cast into a floating-point for the comparison.
Remediation
Except specific cases where we can expect that the value is the same (see http://randomascii.wordpress.com/2012/06/26/doubles-are-not-floats-so-dont-compare-them), the best is to compare the difference with Epsilon a small float number that you can configure according to the accuracy you want.
Violation Code Sample
float32_t x, y;
if ( x == y ) // Non-compliant
if ( x == 0.0f ) // Non-compliant
An indirect test is equally problematic and is also prohibited by this rule:
if ( ( x <= y ) && ( x >= y ) ) // Non-compliant
if ( ( x < y ) || ( x > y ) ) // Non-compliant
Fixed Code Sample
The following is better, but only if the magnitudes are appropriate:
if ( fabs ( x – y ) <=
std::numeric_limits<float>::epsilon( ) ) // Compliant
Reference
MISRA C++, 6-2-2: Floating-point expressions shall not be directly or indirectly tested for equality or inequality
AUTOSAR, C++, 2008, M6-2-2 : Floating-point expressions shall not be directly or indirectly tested for equality or inequality.
Related Technologies
Technical Criterion
CWE-1077 - Floating Point Comparison with Incorrect Operator
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.