---
title: "Lab: summing series in code"
heading: Getting many digits from few terms
eyebrow: A6 · Lesson 31 · Lab: summing series in code
xp: 60
---

::: hook
The alternating harmonic series converges to $\ln 2$, but ten terms leave an error of 0.05, and a million leave $5 \times 10^{-7}$. Libraries don't sum series that way. They estimate the tail they haven't added, or combine a few partial sums to cancel their errors. In this lab you'll sum slow series in Python, then speed them up two ways: Aitken's extrapolation for alternating series, and integral corrections for the tail of a p-series. You'll also add the same terms in a different order and watch the sum move.
:::

::: play
- The stems are the partial sums $S_n$ of $1 - \frac12 + \frac13 - \cdots$. They zigzag around $\ln 2$, closing in only as $1/n$.
- The dashed line is $\ln 2$. Aitken's method takes three neighboring partial sums and extrapolates the zigzag to its center.
- The readout gives the error of $S_n$ and of the Aitken value built from $S_{n-2}$, $S_{n-1}$, $S_n$.
:::

```sim plot
view: graph
x: n = 1..30
y: S = 0.4..1.05
slider: m = 3..30 step 1 = 10
plot: ln(2) + (-1)^(n + 1)/(2*n) | stems | label: partial sums, close to ln 2 ± 1/2n
plot: ln(2) + 0*n | dashed | color: ch2 | label: ln 2
readout: error of the partial sum, about = 1/(2*m) | digits: 3
```

::: predict
## Ten terms of $1 - \frac12 + \frac13 - \cdots$ leave an error of about 0.05. How many terms would plain summing need for an error of $10^{-6}$?

- [ ] About 100
- [ ] About 10 000
- [x] About 500 000
- [ ] It can't reach $10^{-6}$

::: reveal
About 500 000. The error after $n$ terms is about $\frac{1}{2n}$, so $10^{-6}$ needs $n \approx 500\,000$. Aitken's method gets an error near $10^{-4}$ from the first eleven terms, and applying it again does better still: acceleration beats brute force by orders of magnitude.
:::
:::

::: nameit
## Aitken's extrapolation

If the errors of three successive partial sums shrink by a roughly constant factor, the limit is close to

$$A = S_{n+2} - \frac{(S_{n+2} - S_{n+1})^2}{(S_{n+2} - S_{n+1}) - (S_{n+1} - S_n)}$$

It works especially well on alternating series, whose partial sums overshoot and undershoot in a regular pattern.

## Correcting a p-series' tail

For $\sum\frac{1}{n^p}$, add the first $N$ terms, then estimate the rest. The integral $\int_N^\infty x^{-p}dx = \frac{N^{1-p}}{p - 1}$ is the main part of the tail; the Euler–Maclaurin formula adds two smaller corrections:

$$\sum_{n=1}^\infty\frac{1}{n^p} \approx \sum_{n=1}^N\frac{1}{n^p} + \frac{N^{1-p}}{p - 1} - \frac{1}{2N^p} + \frac{p}{12N^{p+1}}$$

With $N = 10$ and $p = 2$ this lands within $4 \times 10^{-7}$ of $\frac{\pi^2}{6}$; the plain partial sum is off by 0.095.

## Rearranging

Taking $a$ positive terms of the alternating harmonic series for each negative one gives $\ln 2 + \frac12\ln a$. Summing it in that order in code shows the sum really moves.
:::

::: example
## Apply Aitken's method to $S_9 = 0.745\,635$, $S_{10} = 0.645\,635$, $S_{11} = 0.736\,544$ of the alternating harmonic series.

::: solution
1. **Take the differences.**
   $$\begin{aligned} S_{10} - S_9 &= -0.1 \\ S_{11} - S_{10} &= +0.090\,909 \end{aligned}$$
2. **Apply Aitken's formula.**
   $$\begin{aligned} A &= S_{11} - \frac{0.090\,909^2}{0.090\,909 + 0.1} \\ &= 0.736\,544 - 0.043\,290 \\ &= 0.693\,254 \end{aligned}$$
3. **Compare.** The true value is 0.693 147: an error of 0.000 11 from partial sums whose own errors are about 0.05.

**Answer:** Aitken's method gives 0.693 254, within 0.000 11 of the true 0.693 147.
:::
:::

::: example
## Estimate $\sum\frac{1}{n^2}$ from ten terms and the tail correction.

::: solution
1. **Add ten terms.** The ten terms add to 1.549 768.
2. **Add the tail corrections.**
   $$\begin{aligned} \frac{10^{-1}}{1} &= 0.1 \\ -\frac{1}{200} &= -0.005 \\ \frac{2}{12 \times 1000} &= 0.000\,167 \end{aligned}$$
   giving 1.644 934.
3. **Compare.** The true value, $\frac{\pi^2}{6}$, is 1.644 934 07: right to six places from ten terms.

**Answer:** ten terms and the tail correction give 1.644 934, right to six places.
:::
:::

::: check
given: n = 10 | 100 | 1000
answer: 1/(2*n)
tolerance: 2%

## About how far is the $n$th partial sum of the alternating harmonic series from $\ln 2$, for $n$ = {n}?

::: right
Right. About $\frac{1}{2n}$ = {answer}.
:::

::: misses
- [1/n] That's the alternating series bound, the next term. The actual error is about half of it.
- [any] Not yet. The partial sums zigzag around the limit by about half a term.
:::
:::

::: check
given: p = 2 | 3 | 4; N = 10 | 100
answer: N^(1 - p)/(p - 1)
tolerance: 0.5%

## What does the integral contribute to the tail of $\sum\frac{1}{n^{\given{p}}}$ after {N} terms?

::: right
Right. $\frac{N^{1-p}}{p - 1}$ = {answer}.
:::

::: misses
- [N^(-p)] That's the next term alone. The tail adds up many terms.
- [any] Not yet. $\int_N^\infty x^{-p}dx$.
:::
:::

::: check
kind: python

## Write `aitken(s)`: given a list of partial sums `s`, return the list of Aitken values from each three consecutive sums. Set `S` to the first 11 partial sums of the alternating harmonic series and `A = aitken(S)`.

```python starter
import math

def aitken(s):
    return s

S = []
A = aitken(S)
print(A[-1:])
```

```python solution
import math

def aitken(s):
    out = []
    for k in range(len(s) - 2):
        a, b, c = s[k], s[k + 1], s[k + 2]
        out.append(c - (c - b)**2 / ((c - b) - (b - a)))
    return out

S = []
total = 0.0
for n in range(1, 12):
    total += (-1)**(n + 1) / n
    S.append(total)
A = aitken(S)
print(A[-1:])
```

```python tests
import math
assert len(S) == 11 and abs(S[-1] - 0.7365440115) < 1e-9, "S should hold the first 11 partial sums."
assert len(A) == 9, "Eleven partial sums give nine Aitken values."
assert abs(A[-1] - math.log(2)) < 2e-4 and abs(S[-1] - math.log(2)) > 0.04, f"The last Aitken value should be within 2e-4 of ln 2; got {A[-1]}."
B = aitken(A)
assert abs(B[-1] - math.log(2)) < 1e-5, "Applying Aitken again should do better still."
```

::: right
Right. Two rounds of Aitken from eleven terms beat a hundred thousand terms of plain summing.
:::
:::

::: check
kind: python
given: p = 2 | 3 | 4

## Write `zeta(p, N)`: the sum of the first `N` terms of $\sum\frac{1}{n^p}$ plus the three tail corrections from the reading. Set `z = zeta(p, 10)` for $p$ = {p}.

```python starter
def zeta(p, N):
    return sum(1 / n**p for n in range(1, N + 1))

z = zeta(p, 10)
print(z)
```

```python solution
def zeta(p, N):
    s = sum(1 / n**p for n in range(1, N + 1))
    return s + N**(1 - p) / (p - 1) - 0.5 * N**(-p) + p * N**(-p - 1) / 12

z = zeta(p, 10)
print(z)
```

```python tests
import math
exact = {2: math.pi**2 / 6, 3: 1.2020569031595942, 4: math.pi**4 / 90}[p]
assert abs(z - exact) < 5e-7, f"With ten terms and the corrections, zeta({p}) should be within 5e-7 of {exact}; got {z}."
plain = sum(1 / n**p for n in range(1, 11))
assert abs(plain - exact) > 1000 * abs(z - exact), "The corrections should improve on the plain sum by far more than a thousandfold."
```

::: right
Right. The tail corrections do the work of hundreds of thousands of terms.
:::
:::

::: check
kind: python
given: a = 2 | 3 | 4

## Write `rearranged(a, groups)`: sum the alternating harmonic series taking `a` positive (odd-denominator) terms, then one negative (even-denominator) term, for `groups` rounds. Set `r = rearranged(a, 100000)` and `target` to $\ln 2 + \frac12\ln a$.

```python starter
import math

def rearranged(a, groups):
    return math.log(2)

r = rearranged(a, 100000)
target = 0
print(r, target)
```

```python solution
import math

def rearranged(a, groups):
    s, pos, neg = 0.0, 1, 2
    for _ in range(groups):
        for _ in range(a):
            s += 1 / pos
            pos += 2
        s -= 1 / neg
        neg += 2
    return s

r = rearranged(a, 100000)
target = math.log(2) + 0.5 * math.log(a)
print(r, target)
```

```python tests
import math
assert abs(target - (math.log(2) + 0.5 * math.log(a))) < 1e-15, "target should be ln 2 + (1/2) ln a."
assert abs(r - target) < 1e-4, f"Taking {a} positive terms per negative one should approach {target:.5f}; got {r:.5f}."
assert abs(rearranged(1, 100000) - math.log(2)) < 1e-4, "One positive per negative is the usual order, summing to ln 2."
```

::: right
Right. The same terms, in a different proportion, add up to a different number: the series converges only conditionally.
:::
:::

::: check
kind: python

## Write `harmonic_N(T)` returning the first $N$ with $H_N = 1 + \frac12 + \cdots + \frac1N \ge T$. Set `n5 = harmonic_N(5)` and compare it with the estimate $e^{T - 0.5772}$.

```python starter
import math

def harmonic_N(T):
    return 1

n5 = harmonic_N(5)
print(n5, math.exp(5 - 0.5772))
```

```python solution
import math

def harmonic_N(T):
    s, n = 0.0, 0
    while s < T:
        n += 1
        s += 1 / n
    return n

n5 = harmonic_N(5)
print(n5, math.exp(5 - 0.5772))
```

```python tests
import math
assert n5 == 83, f"H_N first reaches 5 at N = 83; got {n5}."
assert harmonic_N(8) == 1674, "H_N first reaches 8 at N = 1674."
assert abs(harmonic_N(8) - math.exp(8 - 0.5772)) < 2, "The estimate e^(T - 0.5772) should be within a couple of terms."
```

::: right
Right. The harmonic sum reaches 8 only after 1674 terms: divergence can be very slow.
:::
:::

::: check
kind: python

## Write `sum_until(tol)`: add $\frac{1}{k!}$ for $k = 1, 2, \ldots$, stopping before the first term below `tol`, and return `(total, k)` where `k` is that first small term's index. Check that the total is close to $e - 1$.

```python starter
import math

def sum_until(tol):
    return 0, 0

print(sum_until(1e-12), math.e - 1)
```

```python solution
import math

def sum_until(tol):
    total, k, term = 0.0, 1, 1.0
    while True:
        term /= k
        if term < tol:
            return total, k
        total += term
        k += 1

print(sum_until(1e-12), math.e - 1)
```

```python tests
import math
total, k = sum_until(1e-12)
assert abs(total - (math.e - 1)) < 1e-11 and k == 15, f"Fourteen terms reach e - 1 to 1e-11; got {total} after k = {k}."
assert sum_until(0.1)[1] == 4, "1/4! = 0.042 is the first term below 0.1."
```

::: right
Right. Factorials shrink the terms so fast that fourteen of them give twelve digits.
:::
:::

::: explain
## Why does Aitken's method work so well on the alternating harmonic series' partial sums?

::: model
Aitken's formula assumes the errors of successive partial sums form a geometric sequence, $e_{n+1} \approx \lambda e_n$, and finds the limit that a geometric approach would have. For an alternating series the partial sums jump back and forth across the limit, with errors of nearly equal size and opposite sign, so $\lambda \approx -1$, and the formula essentially averages neighboring partial sums with the right weights to land on the center of the zigzag. The leftover error comes from the errors not being exactly geometric (they shrink like $1/n$), which is why one round gives about $10^{-4}$ and a second round, applied to the already-improved values, gains more. For series whose errors aren't close to geometric, Aitken can help little or even mislead, so it's checked against a known case first.
:::
:::

::: practice

::: check
given: n = 5..5000
answer: 1/(2*n)
tolerance: 3%

## Error of the $n$th alternating harmonic partial sum, about, for $n$ = {n}?

::: misses
- [any] About $\frac{1}{2n}$.
:::
:::

::: check
given: p = 1.5..5; N = 5..1000
answer: N^(1 - p)/(p - 1)
tolerance: 0.5%

## Integral part of the tail of $\sum n^{-\given{p}}$ after {N} terms?

::: misses
- [any] $\frac{N^{1-p}}{p - 1}$.
:::
:::
:::
