2023-05-03 11:06:20 +02:00
== Why is this an issue?
2021-01-27 13:42:22 +01:00
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.
2020-06-30 12:47:33 +02:00
2021-02-02 15:02:10 +01:00
2020-06-30 12:47:33 +02:00
Even simple floating point assignments are not simple:
2020-06-30 14:49:38 +02:00
2020-06-30 12:47:33 +02:00
----
float f = 0.100000001f; // 0.1
double d = 0.10000000000000001; // 0.1
----
(Results will vary based on compiler and compiler settings)
2021-02-02 15:02:10 +01:00
2021-01-27 13:42:22 +01:00
Therefore, the use of the equality (``++==++``) and inequality (``++!=++``) operators on ``++float++`` or ``++double++`` values is almost always an error.
2020-06-30 12:47:33 +02:00
2021-02-02 15:02:10 +01:00
2020-06-30 12:47:33 +02:00
This rule checks for the use of direct and indirect equality/inequality tests on floats and doubles.
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2020-06-30 12:47:33 +02:00
2022-02-04 17:28:24 +01:00
[source,csharp]
2020-06-30 12:47:33 +02:00
----
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
{
// ...
}
----
2021-06-02 20:44:38 +02:00
2021-06-03 09:05:38 +02:00
ifdef::env-github,rspecator-view[]
2021-09-20 15:38:42 +02:00
'''
== Implementation Specification
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== Message
Do not check floating point [in]equality with exact values, use [a range | `FloatingPointTypeName.IsXXX()` | `IsXXX()`] instead.
2021-09-20 15:38:42 +02:00
2021-06-08 15:52:13 +02:00
'''
2021-06-02 20:44:38 +02:00
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
2023-06-22 10:38:01 +02:00
2021-06-03 09:05:38 +02:00
endif::env-github,rspecator-view[]