---
title: "Lab: sequences and series in code"
heading: Thresholds, tail brackets, accelerated sums, pairings and root tests
eyebrow: A14 · Lesson 9 · Lab: sequences and series in code
xp: 60
---

::: hook
Lessons 1 to 8 were about sequences and series in the abstract: ε and N, bounds on tails, rearrangements, countable sets, limsup. In this lab you'll make each idea concrete in code. You'll find ε–N thresholds by search and compare them with the formulas from proofs, bracket $\zeta(3)$ with integrals, accelerate a slowly converging alternating series, check that the Cantor pairing really is a bijection, and watch the root test's k-th roots settle where the ratio test can't decide.
:::

::: play
- The stems are $\lvert a_k\rvert^{1/k}$ for $a_k = 2^{-k}$ (k even) and $3^{-k}$ (k odd). They alternate between exactly ½ and exactly ⅓.
- The limsup is ½ < 1, so the root test says the series converges. The ratios $\frac{a_{k+1}}{a_k}$, by contrast, alternate between values going to 0 and to ∞: the ratio test is silent.
- In the lab you'll compute both sequences and confirm what each test sees.
:::

```sim plot
view: graph
x: k = 1..30
y: r = 0..0.7
plot: 0.5*(1 + cos(pi*k))/2 + (1/3)*(1 - cos(pi*k))/2 | stems | label: k-th root of aₖ
plot: 0.5 | dashed | label: limsup
```

::: predict
## A proof shows $\left\lvert\frac{3n + 1}{n + 2} - 3\right\rvert = \frac{5}{n + 2}$. For ε = 0.0003, what N does a computer search find?

- [ ] About 5000
- [x] 16 665
- [ ] About 1 666
- [ ] It can't be found by search

::: reveal
16 665: the first n with $\frac{5}{n + 2} < 0.0003$, since $n + 2 > 16\,666.7$. Search and formula agree exactly here because the formula is exact; when a proof uses inequalities, its N is larger than the true threshold, and a search shows by how much.
:::
:::

::: nameit
## Searching for N

To find the least N with $\lvert a_n - L\rvert < \varepsilon$ for all n ≥ N, record the last n that fails, and stop once you've gone far past it (for monotone tails, a few times further is plenty). A search can't prove "for all n", but it checks a proof's N and exposes a wrong one.

## Brackets and acceleration

For a decreasing positive f, $S_N + \int_{N+1}^\infty f \le S \le S_N + \int_N^\infty f$. The midpoint of the bracket is usually far more accurate than $S_N$. For alternating series, repeatedly average neighboring partial sums (lesson 7's example, done systematically).

## Pairing in code

`math.isqrt` gives exact integer square roots, so the inverse pairing $w = \left\lfloor\frac{\sqrt{8k + 1} - 1}{2}\right\rfloor$, $n = k - \frac{w(w + 1)}{2}$, $m = w - n$ can be computed without floating-point error.
:::

::: example
## Bracket $\zeta(3) = \sum k^{-3}$ using ten terms.

::: solution
1. **Partial sum.**
   $$S_{10} = 1.197532$$
2. **Bound the tail with integrals.**
   $$\int_{11}^\infty x^{-3}dx = \frac{1}{242}$$
   $$\int_{10}^\infty x^{-3}dx = \frac{1}{200}$$
3. **Bracket.** Adding these to $S_{10}$ gives the bracket [1.201664, 1.202532], whose midpoint is 1.202098.
4. **Compare with the true value.** The true value is 1.2020569, so the midpoint's error is $4 \times 10^{-5}$, against $S_{10}$'s 0.0045.
5. **Going further.** The same idea with more terms or with the Euler–Maclaurin correction gives many digits from a short sum.

**Answer:** $\zeta(3)$ lies in [1.201664, 1.202532], and the midpoint 1.202098 is off by about $4 \times 10^{-5}$.
:::
:::

::: example
## Accelerate the first 20 partial sums of $1 - \frac12 + \frac13 - \cdots$.

::: solution
1. **The raw partial sum.**
   $$S_{20} = 0.668771$$
   which is 0.024 below $\ln 2 = 0.693147$.
2. **Average neighbors three times.** Using the last few partial sums, this leaves an error of $2.9 \times 10^{-6}$, more than 8000 times smaller than before, for no extra terms.
3. **Why it works.** The partial sums alternate around the limit with slowly shrinking swings; each averaging cancels most of the current swing.

**Answer:** three rounds of averaging cut the error from 0.024 to $2.9 \times 10^{-6}$.
:::
:::

::: check
given: c = 5 | 10; e = 0.001 | 0.0003
answer: floor(c/e - 2) + 1
tolerance: 0

## For $\left\lvert a_n - L\right\rvert = \frac{\given{c}}{n + 2}$, what is the least N with $\lvert a_n - L\rvert < \given{e}$ for all n ≥ N?

::: right
Right. Solve $\frac{c}{n + 2} < \varepsilon$: the first whole n above $\frac c\varepsilon - 2$.
:::

::: misses
- [any] $n + 2 > \frac{c}{\varepsilon}$.
:::
:::

::: check
given: k = 18 | 100 | 1000
answer: floor((sqrt(8*k + 1) - 1)/2)
tolerance: 0

## Inverting the Cantor pairing at k = {k}, which diagonal w = m + n is it on?

::: right
Right. The largest w with $\frac{w(w + 1)}{2} \le k$.
:::

::: misses
- [any] $\left\lfloor\frac{\sqrt{8k + 1} - 1}{2}\right\rfloor$.
:::
:::

::: check
kind: python

## Write `first_N(a, L, eps)` that searches for the least N with $\lvert a(n) - L\rvert < \varepsilon$ for all n ≥ N (track the last failing n; stop when n exceeds ten times that plus 100). Set `N1` for $a_n = \frac{3n + 1}{n + 2}$, L = 3, ε = 0.0003, and `N2` for $a_n = \frac{n}{2^n}$, L = 0, ε = 0.001.

```python starter
def first_N(a, L, eps):
    return 1

N1 = first_N(lambda n: (3 * n + 1) / (n + 2), 3, 0.0003)
N2 = first_N(lambda n: n / 2**n, 0, 0.001)
print(N1, N2)
```

```python solution
def first_N(a, L, eps):
    bad, n = 0, 1
    while n <= 10 * bad + 100:
        if abs(a(n) - L) >= eps:
            bad = n
        n += 1
    return bad + 1

N1 = first_N(lambda n: (3 * n + 1) / (n + 2), 3, 0.0003)
N2 = first_N(lambda n: n / 2**n, 0, 0.001)
print(N1, N2)
```

```python tests
assert N1 == 16665, f"5/(n + 2) < 0.0003 first holds at n = 16665; got {N1}."
assert N2 == 14, f"n/2^n < 0.001 for all n >= 14; got {N2}."
```

::: right
Right. 16 665 and 14, matching the formulas from the proofs.
:::
:::

::: check
kind: python

## Set `lo` and `hi` to the integral-test bracket for $\zeta(3)$ from $S_{10}$, and `mid` to its midpoint.

```python starter
lo = hi = mid = 0.0
print(lo, hi, mid)
```

```python solution
S10 = sum(1 / k**3 for k in range(1, 11))
lo = S10 + 1 / (2 * 11**2)
hi = S10 + 1 / (2 * 10**2)
mid = (lo + hi) / 2
print(lo, hi, mid)
```

```python tests
zeta3 = 1.2020569031595942
assert lo < zeta3 < hi, f"The bracket [{lo}, {hi}] should contain zeta(3)."
assert abs(mid - zeta3) < 5e-5, f"The midpoint should be within 5e-5; got {mid}."
```

::: right
Right. [1.201664, 1.202532], with the midpoint 1.202098 within $4 \times 10^{-5}$.
:::
:::

::: check
kind: python

## Set `S` to the first 20 partial sums of $\sum\frac{(-1)^{k+1}}{k}$ (a NumPy array), then average neighbors three times (`A = (A[:-1] + A[1:]) / 2`) and set `err_raw` and `err_acc` to the errors of `S[-1]` and the last averaged value against ln 2.

```python starter
import math
import numpy as np

S = np.zeros(20)
err_raw = err_acc = 1.0
print(err_raw, err_acc)
```

```python solution
import math
import numpy as np

S = np.cumsum([(-1)**(k + 1) / k for k in range(1, 21)])
A = S.copy()
for _ in range(3):
    A = (A[:-1] + A[1:]) / 2
err_raw = abs(S[-1] - math.log(2))
err_acc = abs(A[-1] - math.log(2))
print(err_raw, err_acc)
```

```python tests
assert abs(err_raw - 0.024376) < 1e-5, f"The 20th partial sum is off by 0.0244; got {err_raw}."
assert err_acc < 5e-6, f"Three averagings should bring the error below 5e-6; got {err_acc}."
```

::: right
Right. From 0.024 to $2.9 \times 10^{-6}$ with the same twenty terms.
:::
:::

::: check
kind: python

## Write `pair(m, n)` and `unpair(k)` for the Cantor pairing (use `math.isqrt`). Set `ok` to whether `pair(*unpair(k)) == k` for all k below 10 000, and `distinct` to the number of different values of `pair(m, n)` for 0 ≤ m, n < 100.

```python starter
import math

def pair(m, n):
    return m + n

def unpair(k):
    return 0, k

ok = all(pair(*unpair(k)) == k for k in range(10000))
distinct = len({pair(m, n) for m in range(100) for n in range(100)})
print(ok, distinct)
```

```python solution
import math

def pair(m, n):
    return (m + n) * (m + n + 1) // 2 + n

def unpair(k):
    w = (math.isqrt(8 * k + 1) - 1) // 2
    n = k - w * (w + 1) // 2
    return w - n, n

ok = all(pair(*unpair(k)) == k for k in range(10000))
distinct = len({pair(m, n) for m in range(100) for n in range(100)})
print(ok, distinct)
```

```python tests
assert pair(2, 3) == 18 and unpair(18) == (2, 3), "pair(2, 3) is 18 and unpair(18) is (2, 3)."
assert ok, "unpair must invert pair for every k."
assert distinct == 10000, f"Different pairs must give different numbers; got {distinct} distinct values."
```

::: right
Right. Every number below 10 000 comes from exactly one pair, and the 10 000 pairs give 10 000 different numbers.
:::
:::

::: check
kind: python

## For $a_k = 2^{-k}$ (k even) and $3^{-k}$ (k odd), set `roots` to $\lvert a_k\rvert^{1/k}$ for k = 1 to 200, and `ratios` to $\frac{a_{k+1}}{a_k}$ for k = 1 to 30. Set `limsup_est` to the largest root among k ≥ 100, and `ratio_max` to the largest ratio.

```python starter
roots = ratios = [0.0]
limsup_est = ratio_max = 0.0
print(limsup_est, ratio_max)
```

```python solution
a = lambda k: 2.0**-k if k % 2 == 0 else 3.0**-k
roots = [a(k)**(1 / k) for k in range(1, 201)]
ratios = [a(k + 1) / a(k) for k in range(1, 31)]
limsup_est = max(roots[99:])
ratio_max = max(ratios)
print(limsup_est, ratio_max)
```

```python tests
assert abs(limsup_est - 0.5) < 1e-12, f"The roots on even k are exactly 1/2; got {limsup_est}."
assert ratio_max > 1000, f"The ratios grow without bound on odd k; got a max of {ratio_max}."
```

::: right
Right. The root test sees ½ and settles convergence; the ratios swing past 1000 and decide nothing.
:::
:::

::: explain
## Why can a computer search check a proof's N but never replace the proof?

::: model
A search can only examine finitely many n, while the definition of a limit makes a claim about every n beyond N. If the sequence behaved well up to a billion and then misbehaved, no feasible search would notice. What makes a search trustworthy is extra knowledge, usually from a proof, that the tail is monotone or otherwise controlled, so that once the terms are inside the ε band and moving the right way they stay there. Used that way, search is a strong check: a proof's N that's smaller than the searched threshold is wrong, and one much larger shows where the proof's inequalities were loose.
:::
:::

::: practice

::: check
given: c = 2 | 7; e = 0.01 | 0.002
answer: floor(c/e - 2) + 1
tolerance: 0

## Least N for $\frac{\given{c}}{n + 2} < \given{e}$?

::: misses
- [any] First n above $\frac c\varepsilon - 2$.
:::
:::

::: check
given: k = 10 | 45 | 100 | 250 | 500 | 1000
answer: floor((sqrt(8*k + 1) - 1)/2)
tolerance: 0

## Cantor diagonal of k = {k}?

::: misses
- [any] Largest w with $\frac{w(w + 1)}{2} \le k$.
:::
:::
:::
