Floating point innacuracies
Posted
by
Greg
on Stack Overflow
See other posts from Stack Overflow
or by Greg
Published on 2011-01-01T20:30:21Z
Indexed on
2011/01/01
20:54 UTC
Read the original article
Hit count: 178
c++
|floating-point
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?
© Stack Overflow or respective owner