# Loops in C++: Minimizing Numeric Errors

Using floating-point numbers in the loop continuation condition may cause numeric errors.

Numeric errors involving floating-point numbers are inevitable. This section discusses how to minimize such errors.

Listing 5.9 presents an example summing a series that starts with 0.01 and ends with 1.0. The numbers in the series will increment by 0.01, as follows: 0.01 + 0.02 + 0.03 and so on.

Listing 5.9 TestSum.cpp

1 #include <iostream>

2 using namespace std;

3

4 int main()

5 {

6    // Initialize sum

7    double sum = 0;

8

9    // Add 0.01, 0.02, . . . , 0.99, 1 to sum

10    for (double i = 0.01; i <= 1.0; i = i + 0.01)

11    sum += i;

12

13    // Display result

14    cout << “The sum is ” << sum << endl;

15

16    return 0;

17 }

The result is 49.5, but the correct result should be 50.5. What happened? For each itera­tion in the loop, i is incremented by 0.01. When the loop ends, the i value is slightly larger than 1 (not exactly 1). This causes the last i value not to be added into sum. The fundamental problem is that the floating-point numbers are represented by approximation.

To fix the problem, use an integer count to ensure that all the numbers are added to sum.

Here is the new loop:

double currentValue = 0.01;

for (int count = 0; count < 100; count++)

{

sum += currentValue;

currentValue += 0.01;

}

After this loop, sum is 50.5.

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.