refer to relevant problems instead of re-implementing

This commit is contained in:
filifa
2025-05-15 23:30:57 -04:00
parent 275bfae648
commit fc7c74c323
2 changed files with 34 additions and 58 deletions

View File

@@ -36,7 +36,7 @@
"id": "396468b7",
"metadata": {},
"source": [
"If we wanted to compute the convergents ourselves, we could first make a generator for the partial denominators of the continued fraction of $e$."
"To compute the convergents ourselves, we'll first make a generator for the partial denominators of the continued fraction of $e$."
]
},
{
@@ -48,14 +48,9 @@
"source": [
"from itertools import count, chain\n",
"\n",
"def partial_denominators_e(n):\n",
"def partial_denominators_e():\n",
" yield 2\n",
" denominators = chain.from_iterable((1, 2 * k, 1) for k in count(1))\n",
" for (i, b) in enumerate(denominators):\n",
" if i >= n:\n",
" break\n",
" \n",
" yield b"
" yield from chain.from_iterable((1, 2 * k, 1) for k in count(1))"
]
},
{
@@ -63,7 +58,7 @@
"id": "33288cd0",
"metadata": {},
"source": [
"Then write a function for computing a continued fraction from a sequence of partial denominators (outside of SageMath, you might want to use a [fraction type](https://docs.python.org/3/library/fractions.html))."
"Then we'll apply a simple algorithm for computing [convergents using the partial denominators](https://en.wikipedia.org/wiki/Simple_continued_fraction) (outside of SageMath, you might want to use a [fraction type](https://docs.python.org/3/library/fractions.html))."
]
},
{
@@ -73,13 +68,21 @@
"metadata": {},
"outputs": [],
"source": [
"def cf(denominators):\n",
" a = next(denominators)\n",
" \n",
" try:\n",
" return a + 1 / cf(denominators)\n",
" except StopIteration:\n",
" return a"
"def convergents(partial_denoms):\n",
" h, hprev = 1, 0\n",
" k, kprev = 0, 1\n",
" for b in partial_denoms:\n",
" h, hprev = b * h + hprev, h\n",
" k, kprev = b * k + kprev, k\n",
" yield h/k"
]
},
{
"cell_type": "markdown",
"id": "99b790f3",
"metadata": {},
"source": [
"Now just iterate until we reach the 100th convergent."
]
},
{
@@ -100,7 +103,11 @@
}
],
"source": [
"sum(cf(partial_denominators_e(99)).numerator().digits())"
"for (i, c) in enumerate(convergents(partial_denominators_e())):\n",
" if i == 99:\n",
" break\n",
"\n",
"sum(c.numerator().digits())"
]
},
{