the 0, not easy

hey everyone,now I have a question about...
see
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*zenoc's paradox
 *this program calculate the sum of  1/2, 1/4, 1/8, 1/16 ...
 */
#include <iostream>

using namespace std;

int main()
{
	double sum, term;
	int times=0;

	sum = 0.0;
	term = 0.5;
	while (term != 0) {
		times++;
		sum += term;
		term /= 2;
	}
	cout << sum << endl;
	cout << times << endl;
	return 0;
}

the result is
1
1074

But if change the condition of while to
while (sum != sum + term)
the result is
1
63

how can it be so different, can
sum = sum + term
while
term != 0
?
waiting for your answer, thanks.
Last edited on
You shouldn't test for equality with floating point numbers. You need to check if they're within the same epsilon, DBL_EPSILON in your case as you're using doubles.
This should be caused by floating point lack of precision, check the value of numeric_limits<double>::epsilon() which is the minimum value so that 1 != 1+ε
Yeah, round up "errors"
Mathematically the loop doesn't even end ;)
Actually it does...(1/2)^n converges by the n-th term test. It is also a geometric series with r < 1.

http://en.wikipedia.org/wiki/Geometric_series
http://en.wikipedia.org/wiki/N-th_term_test
This series asymptotically approaches 1, which means that f(n)=sigma(i=[1;n])(2^-i)=1-2^-n. For example, f(3) = 1/2+1/4+1/8 = 1-1/8.
There's no need to do this iteratively. Just choose a large enough value for n and solve it in a single line.
Topic archived. No new replies allowed.