Float or Double Loop Counter
ID |
java.float_loop_counter |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
reliability |
Description
Reports for-loops whose counter variable is declared as float or double. Floating-point arithmetic is subject to rounding errors, which can cause the loop to iterate one too many or one too few times.
Rationale
Floating-point values cannot represent all decimal fractions exactly. Incrementing 0.0f by 0.1f ten times does not yield exactly 1.0f, so a loop condition f < 1.0f may behave unexpectedly.
// Bad - may iterate 9 or 11 times instead of 10
for (float f = 0.0f; f < 1.0f; f += 0.1f) {
process(f);
}
Remediation
Use an integer counter and compute the floating-point value inside the loop body.
// Good - precise iteration count
for (int i = 0; i < 10; i++) {
float f = i * 0.1f;
process(f);
}