Computers can represent only a finite number of digits. It is therefore impossible to precisely represent repeating binary-representation values such as 1/3 or 1/5 with the most common floating-point representation: binary floating point.
When precise computation is necessary, use alternative representations that can accurately represent the values. For example, if you are performing arithmetic on decimal values and need an exact decimal rounding, represent the values in binary-coded decimal instead of using floating-point values. Another option is decimal floating-point arithmetic, as specified by ANSI/IEEE 754-2007. ISO/IEC WG14 has drafted a proposal to add support for decimal floating-point arithmetic to the C language [ISO/IEC DTR 24732].
When precise computation is necessary, carefully and methodically estimate the maximum cumulative error of the computations, regardless of whether decimal or binary is used, to ensure that the resulting error is within tolerances. Consider using numerical analysis to properly understand the problem. An introduction can be found in David Goldberg's "What Every Computer Scientist Should Know about Floating-Point Arithmetic" [Goldberg 1991].
Noncompliant Code Example
This noncompliant code example takes the mean of 10 identical numbers and checks to see if the mean matches this number. It should match because the 10 numbers are all
10.1. Yet, because of the imprecision of floating-point arithmetic, the computed mean does not match this number.
On a 64-bit Linux machine using GCC 4.1, this program yields the following output:
The noncompliant code can be fixed by replacing the floating-point numbers with integers for the internal additions. Floats are used only when printing results and when doing the division to compute the mean.
On a 64-bit Linux machine using GCC 4.1, this program yields the following expected output:
Using a representation other than floating point may allow for more accurate results.
|Axivion Bauhaus Suite|
Can detect violations of this recommendation. In particular, it checks to see if the arguments to an equality operator are of a floating-point type
|LDRA tool suite|
|56 S||Partially implemented|
|Floating-point expressions shall not be tested for equality or inequality|
|Polyspace Bug Finder|
|Floating point comparison with equality operators|
Imprecise comparison of floating-point variables
Search for vulnerabilities resulting from the violation of this recommendation on the CERT website.