Because floating-point numbers can represent fractions, it is often mistakenly assumed that they can represent any simple fraction exactly. In fact, floating-point numbers are subject to precision limitations just as integers are, and binary floating-point numbers cannot represent all decimal fractions exactly, even if they the fractions can be represented in a small number of decimal digits.
...
Noncompliant Code Example
In this This noncompliant code example , uses a floating-point variable is used as a loop counter. The decimal number 0.1 is a repeating fraction in binary and cannot be exactly represented as a binary floating-point number.
Code Block | ||
---|---|---|
| ||
for (float x = 0.1f; x <= 1.0f; x += 0.1f) { // ... } |
This loop is executed executes only nine times. (If the value of x
is printed inside the loop, the following values appear: 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.70000005, 0.8000001, 0.9000001.)
Compliant Solution
In this This compliant solution , the uses an integer loop counter is an integer from which the floating-point value is derived.
...
Noncompliant Code Example
In this This noncompliant code example , uses a floating-point loop counter that is incremented by an amount that is too small to change its value given its the precision.
Code Block | ||
---|---|---|
| ||
for (float x = 100000001.0f; x <= 100000010.0f; x += 1.0f) { /* ... */ } |
This produces an infinite loop.
Compliant Solution
In this This compliant solution , the uses an integer loop counter is an integer from which the floating-point value is derived. Additionally, a double
is used instead of a float
to gain enough precision.
...