...
By definition, a floating-point number is of finite precision and, regardless of the underlying implementation, is prone to errors associated with rounding. (See guidelines recommendations FLP01-C. Take care in rearranging floating point expressions and FLP02-C. Avoid using floating point numbers when precise computation is needed.).
The most common floating-point system is specified by the IEEE 754 standard. An older floating-point system is the IBM floating-point representation (sometimes referred to as IBM/370). Each of these systems has differing precisions and ranges of representable values. As a result, they do not represent all of the same values, are not binary compatible, and have differing associated error rates.
...
On 64-bit Linux, with GCC Compiler 4.1, this produces:
| Code Block |
|---|
Float is 0.33333334326744079589843750000000000000000000000000 |
On Windows XP, with Microsoft Visual C++ Compiler 9.0, this produces:
| Code Block |
|---|
Float is 0.33333334326744080000000000000000000000000000000000 |
...
| Wiki Markup |
|---|
The reason for this behavior is that Linux uses the internal extended precision mode of the x87 floating-point unit (FPU) on IA-32 machines for increased accuracy during computation. When the result is stored into memory by the assignment to {{c}}, the FPU automatically rounds the result to fit into a {{double}}. The value read back from memory now compares unequally to the internal representation, which has extended precision. Windows does not use the extended precision mode, so all computation is done with double precision, and there are no differences in precision between values stored in memory and those internal to the FPU. For GCC, compiling at optimization level 1 or higher eliminates the unnecessary store into memory, so all computation happens within the FPU with extended precision \[[Gough 2005|AA. Bibliography#Gough 2005]\]. |
...
Search for vulnerabilities resulting from the violation of this recommendation on the CERT website.
Related Guidelines
CERT C++ Secure Coding Standard: FLP00-CPP. Understand the limitations of floating point numbers
ISO/IEC 9899:1999 Section 5.2.4.2.2, "Characteristics of floating types <float.h>"
ISO/IEC TR 24772 "PLF Floating Point Arithmetic"
Bibliography
| Wiki Markup |
|---|
\[[Gough 2005|AA. Bibliography#Gough 2005]\] [Section 8.6, "Floating-point issues"|http://www.network-theory.co.uk/docs/gccintro/gccintro_70.html]
\[[IEEE 754 2006|AA. Bibliography#IEEE 754 2006]\]
\[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\] Section 5.2.4.2.2, "Characteristics of floating types {{<float.h>}}"
\[[ISO/IEC PDTR 24772|AA. Bibliography#ISO/IEC PDTR 24772]\] "PLF Floating Point Arithmetic" |
...
05. Floating Point (FLP) 05. Floating Point (FLP) FLP01-C. Take care in rearranging floating point expressions