TICS Coding Standard Viewer 
TIOBE Software Quality Framework
Print-friendly version
©TIOBE Software www.tiobe.com
C# Coding Standard

Rule:  10@401Checked automatically with code checker

Synopsis:Floating point values shall not be compared using the == nor the != operators nor the Equals method.
Severity Level:2
Category:Data types


Most floating point values have no exact binary representation and have a limited precision, which can even decrease by rounding errors, especially when intermediately using integral values. Thus comparing these using == resp. != will often not lead to the desired results.

The way to solve this is to define an helper function that takes a range that determines whether two floating point values are the same. E.g.

public static bool AlmostEquals(double double1, double double2, double precision)
    return (Math.Abs(double1 - double2) <= precision);
double d1;
double d2;
bool equals = AlmostEquals(d1, d2, 0.0000001);

It is important to understand that it is wrong to use a fixed constant to compare to because the value of this constant depends on the expected values of the floating points. Big floats need a larger precision than small floats. That's why comparing to constant Epsilon is not correct. Epsilon might be too small in some cases to perform a correct comparison.

Exception to the rule When a floating point variable is explicitly initialized with a value such as 1.0 or 0.0, and then checked for a change at a later stage.