Synopsis: | Floating point values shall not be compared using the == nor the != operators nor the Equals method. |
Language: | C# |
Severity Level: | 2 |
Category: | Data types |
Description: |
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 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
|