Greg
Greg

Reputation: 13

Floating point inaccuracies

While writing a function which will perform some operation with each number in a range I ran into some problems with floating point inaccuracies. The problem can be seen in the code below:

#include <iostream>

using namespace std;

int main()
{
    double start = .99999, end = 1.00001, inc = .000001;
    int steps = (end - start) / inc;

    for(int i = 0; i <= steps; ++i)
    {
        cout << (start + (inc * i)) << endl;
    }
}

The problem is that the numbers the above program outputs look like this:

0.99999
0.999991
0.999992
0.999993
0.999994
0.999995
0.999996
0.999997
0.999998
0.999999
1
1
1
1
1
1.00001
1.00001
1.00001
1.00001
1.00001
1.00001

They only appear to be correct up to the first 1. What is the proper way to solve this problem?

Upvotes: 1

Views: 1363

Answers (2)

chrisaycock
chrisaycock

Reputation: 37928

Your sample output only looks wrong because of how ostream rounds by default. You can set precision to get some other output.

cout.precision(10);
cout << (start + (inc * i)) << endl;

Here's what I get now:

0.99999
0.999991
0.999992
0.999993
0.999994
0.999995
0.999996
0.999997
0.999998
0.999999
1
1.000001
1.000002
1.000003
1.000004
1.000005
1.000006
1.000007
1.000008
1.000009
1.00001

Upvotes: 4

Related Questions