AutosarC++18_10-M6.2.2¶
Floating-point expressions shall not be directly or indirectly tested for equality or inequality
Required inputs: IR
| Level | required |
|---|---|
| Target | implementation |
| Enforcement | partially automated |
Rationale
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 behaviour 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<float>::epsilon()) and the magnitude of the numbers being compared.
Example
The result of the test in the following code is unpredictable:
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
The following is better, but only if the magnitudes are appropriate:
if ( fabs ( x – y ) <=
std::numeric_limits<float>::epsilon( ) ) // Compliant
Note
For legal reasons, this rule’s description is not part of the public documentation.