46 lines
1.3 KiB
Plaintext
46 lines
1.3 KiB
Plaintext
Floating point math is imprecise because of the challenges of storing such values in a binary representation. Even worse, floating point math is not associative; push a ``++float++`` or a ``++double++`` through a series of simple mathematical operations and the answer will be different based on the order of those operation because of the rounding that takes place at each step.
|
|
|
|
|
|
Even simple floating point assignments are not simple:
|
|
|
|
----
|
|
float f = 0.100000001f; // 0.1
|
|
double d = 0.10000000000000001; // 0.1
|
|
----
|
|
|
|
(Results will vary based on compiler and compiler settings)
|
|
|
|
|
|
Therefore, the use of the equality (``++==++``) and inequality (``++!=++``) operators on ``++float++`` or ``++double++`` values is almost always an error.
|
|
|
|
|
|
This rule checks for the use of direct and indirect equality/inequality tests on floats and doubles.
|
|
|
|
== Noncompliant Code Example
|
|
|
|
----
|
|
float myNumber = 3.146f;
|
|
if ( myNumber == 3.146f ) //Noncompliant. Because of floating point imprecision, this will be false
|
|
{
|
|
// ...
|
|
}
|
|
|
|
if (myNumber <= 3.146f && mNumber >= 3.146f) // Noncompliant indirect equality test
|
|
{
|
|
// ...
|
|
}
|
|
|
|
if (myNumber < 4 || myNumber > 4) // Noncompliant indirect inequality test
|
|
{
|
|
// ...
|
|
}
|
|
----
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
include::../comments-and-links.adoc[]
|
|
endif::env-github,rspecator-view[]
|