/*zenoc's paradox
*this program calculate the sum of 1/2, 1/4, 1/8, 1/16 ...
*/
#include <iostream>
usingnamespace 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
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+ε
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.