Q:

Recurrence relation with python.

How to find the terminating value of the continued fractions 
$$
S=3-\cfrac2{3-\cfrac2{3-\cfrac2{\ddots}}}
$$
by writing a recurrence relation in Python? (Start from any guess value other than 1.)

A:

Write your equation as $$S=3-\frac{2}S$$
Notice that $S=1$ is a solution, however I think it's unstable. Then just start with any number $S_0$ not equal to $1$. Then repeat $$S_{n}=3-\frac2{S_{n-1}}$$
until $|S_n-S_{n-1}|<\varepsilon$.
Additional:
Following the comment from @RobArthan, let's see what's happening if you are close to either of the two solutions $S=1$ or $S=2$.
Let's choose $S_n=1+\alpha$, where $|\alpha|\ll1$. Then $$S_{n+1}-1=3-\frac 2{1+\alpha}-1=\frac{2\alpha}{1+\alpha}\approx2\alpha$$
So starting from any point in the vicinity of $1$ the next iteration will be further away (about a factor of $2$ further than the initial condition).
How about $2$? We repeat the same steps: $S_n=2+\alpha$
$$S_{n+1}-2=3-\frac{2}{2+\alpha}-2=\frac{\alpha}{2+\alpha}\approx\frac\alpha2$$
So starting close to $2$, in the next step you are getting twice as close as before. Therefore $2$ is a stable solution

A:

For a suitable function $f$, we can iterate an estimate $S$ to $f(S)$ with a for loop, terminated either when the change in $S$ is small or after a large number of iterations. Fewer iterations are needed if $f$ is Newton-Raphson inspired than if you just use $f(S):=3-2/S$. In particular, $S=3-2/S\implies S^2-3S+2=0$, so you could choose $f(S)=S-\frac{S^2-3S+2}{2S-3}=\frac{S^2-2}{2S-3}$.
Of course, there's no need to iterate anyway, as clearly $S=3-2/S\implies S\in\{1,\,2\}$. Mathematically, there are two interesting questions: which value of $S$ if either is mandated by the definition of $S$ (is it even well-defined?), and which choice of $f$ gives stable convergence to such a value from a wide range of nearby estimates of $S$?
We must define $S$ as the limit of a sequence. The obvious choice is $S_0:=3,\,S_{n+1}:=3-\frac{2}{S_n}$. You can easily prove by induction that $S_n\in(2,\,3]$, so $S=2$; $S\ne1$. However, you'll find an estimate close to either $1$ or $2$ leads to stable behaviour with the above Newton-Raphson choice of iteration. (This can be proven by considering the first few derivatives of $f$.)

