My code is supposed to calculate the 100th element of the sequence $x_0=1 ; x_i=\dfrac{x_{i-1}+1}{x_{i-1}+2}, i=1,2, \ldots$
I wrote iterative and recursive functions, but the results are not equal. Is it due to the lost of decimals?
Here is my driver code. The data from the file is i=100.
int main()
{
int i;
ifstream f ("data.txt");
f >> i;
double x_0= 1.00;
double x_100 = l(x_0, i);
ofstream g ("results.txt", ios::app);
g <<"\n100th element (by looping): " << x_100;
x_100 = r(x_0);
g <<"\n100th element (by recursion): " << x_100;
return 0;
}
l() is iterative function,
r() is recursive function
double l(double x, int i)
{
for (int j = 0; j<i ; j++){
x = (x + 1)/(x+2);
}
return x;
}
double r(double x)
{
if (x == 0)
return 1;
else
return (r(x-1) + 1) / (r(x-1) + 2);
}
Here are the results
100th element (by looping): 0.618034
100th element (by recursion): 0.666667
I the recursive function you do
With
x == 1.0that's equal toThat's of course equal to
And since
r(0)will return1that equation isThere's no further recursion. The result is
2.0 / 3.0which is0.66667.The iterative function
lon the other hand will do100iterations where each iteration will change the value ofx, making it even smaller and smaller.The functions simply does different things, leading to different results.