I've completed a problem that involves approximating $e$ by a continued fraction:
$$\frac{N_1}{D_1+\frac{N_2}{D_2+\frac{N_3}{\ddots+\frac{N_k}{D_k}}}}$$
with the $N_i$ being the list {1,1,1, …}
and the $D_i$ being the list {1,2,1,1,4,1,1,6,1,1,8, …}
. (Note: The continued fraction actually approximates $e-2$).
The overarching structure of computing the continued fraction is a straightforward application of Fold
with the following function defined:
f[x_, {m_, d_}] := m/(d+x);
eContFracApprox[n_] := Fold[f, 0, (*properly constructed list of pairs*)]
which shifts the crux of the problem to generating the lists for $N_i$ and $D_i$ and combining them properly.
I have a solution, but I'm not happy with it:
Reverse[
MapThread[
List, {Table[1, {n}],
Take[Flatten[{Join[{1, 2}, Table[{1, 1, i}, {i, 4, n, 2}]]}],n]}
]
]
I think it's ugly and it doesn't work for values of $n < 3$. Perhaps someone can suggest a different/better approach? Specifically, I'd like to know if we can do away completely with MapThread
and generate the list of pairs directly from an application of Table
.
Edit 1:
Just to be clear. I'm looking for an improvement to generating the lists of the $N_i$ and $D_i$. Although, alternate ways of generating continued fractions are also appreciated.
I'll also add my complete function for reference:
eContinuedFractionApprox[n_Integer] := Module[{f},
f[x_, {m_, d_}] := m/(d + x);
N[Fold[f, 0,
Reverse[
MapThread[List,
{Table[1, {n}], Take[Flatten[{Join[{1, 2}, Table[{1, 1, i},
{i, 4, n, 2}]]}],
n]
}
]
]
],
n
] + 2
]