Care must be taken Be careful when rearranging floating-point expressions to ensure the greatest accuracy of the result.
Wiki Markup |
---|
According to C99, Section 5.1.2.3, "Program execution" \[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\]: |
Rearrangement for floating-point expressions is often restricted because of limitations in precision as well as range. The implementation cannot generally apply the mathematical associative rules for addition or multiplication, nor the distributive rule, because of roundoff error, even in the absence of overflow and underflow. Likewise, implementations cannot generally replace decimal constants to rearrange expressions. In the following fragment, rearrangements suggested by mathematical rules for real numbers are often not valid.
Code Block double x, y, z; /* ... */ x = (x * y) * z; /* not equivalent to x *= y * z; */ z = (x - y) + y ; /* not equivalent to z = x; */ z = x + x * y; /* not equivalent to z = x * (1.0 + y); */ y = x / 5.0; /* not equivalent to y = x * 0.2; */
...
Search for vulnerabilities resulting from the violation of this rule recommendation on the CERT website.
Other Languages
Related Guidelines
This rule appears in the C++ Secure Coding Standard as : FLP01-CPP. Take care in rearranging floating point expressions.This rule appears in
the Java Secure Coding Standard as : FLP01-J. Take care in rearranging floating point expressions.
Bibliography
Wiki Markup |
---|
\[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\] Section 5.1.2.3, "Program execution" \[[ISO/IEC PDTR 24772|AA. Bibliography#ISO/IEC PDTR 24772]\] "PLF Floating Point Arithmetic" |
...