Floating-point variables must not be used as loop counters. Limited-precision IEEE 754 floating-point types cannot represent
- all All simple fractions exactly.
- all All decimals precisely, even when the decimals can be represented in a small number of digits.
- all All digits of large values, meaning that incrementing a large floating-point value might not change that value within the available precision.
...
This compliant solution uses an integer loop counter from which the desired floating-point value is derived.:
Code Block | ||
---|---|---|
| ||
for (int count = 1; count <= 10; count += 1) { float x = count/10.0f; System.out.println(x); } |
...
This noncompliant code example uses a floating-point loop counter that is incremented by an amount that is typically too small to change its value given the precision.:
Code Block | ||
---|---|---|
| ||
for (float x = 100000001.0f; x <= 100000010.0f; x += 1.0f) { /* ... */ } |
...
This compliant solution uses an integer loop counter from which the floating-point value is derived. Additionally, it uses a double
to ensure that the available precision suffices to represent the desired values. The solution also runs in strict floating-point (FP-strict) mode to guarantee portability of its results . See (see NUM53-J. Use the strictfp modifier for floating-point calculation consistency across platforms for more information).
Code Block | ||
---|---|---|
| ||
for (int count = 1; count <= 10; count += 1) { double x = 100000000.0 + count; /* ... */ } |
...
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
NUM09-J | lowLow | probableProbable | lowLow | P6 | L2 |
Automated Detection
Automated detection of floating-point loop counters is straightforward.
...
Bibliography
Puzzle 34. , "Down for the countCount" | |
[JLS 2005] | |
[Seacord 2015] | NUM09-J. Do not use floating-point variables as loop counters LiveLesson |
...