...
- All simple fractions exactly.
- All decimals precisely, even when the decimals can be represented in a small number of digits.
- All digits of large values, meaning that incrementing a large floating-point value might not change that value within the available precision.
For the purpose of this rule, a loop counter is an induction variable that is used as an operand of a comparison expression that is used as the controlling expression of a do, while or for loop. An induction variable is a variable that gets increased or decreased by a fixed amount on every iteration of a loop [Aho 1986]. Furthermore, the change to the variable must occur directly in the loop body (rather than inside a function executed within the loop.)
This rule is a subset of NUM04-J. Do not use floating-point numbers if precise computation is required.
Noncompliant Code Example
...
Using floating-point loop counters can lead to unexpected behavior.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
NUM09-J | Low | Probable | Low | P6 | L2 |
Automated Detection
Automated detection of floating-point loop counters is straightforward.
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
Parasoft Jtest |
| CERT.NUM09.FPLI | Do not use floating point variables as loop indices | ||||||
PVS-Studio |
| V6108 |
Related Guidelines
FLP30-C. Do not use floating-point variables as loop counters | |
ISO/IEC TR 24772:2010 | Floating-point Arithmetic [PLF] |
Bibliography
...
...