# series

> infinite sums that add up to a number, and polynomials that match a function near a point.

source: https://learning.anthnydas.com/math/series/

## tl;dr

a series is a sum that keeps going. add the terms one at a time, and if those running totals close in on a number, that number is the sum. a taylor series writes a function as one, with the derivatives at a point as its coefficients.

- **converges:** Sₙ → S (the partial sums close in on a number)
- **geometric:** a/(1 − r) (for |r| < 1. 1/2 + 1/4 + 1/8 + ... = 1)
- **terms → 0:** not enough (1 + 1/2 + 1/3 + ... passes every number)
- **taylor coefficients:** f⁽ⁿ⁾(a)/n! (match the value and every slope at a)
- **eˣ:** Σ xⁿ/n! (for every x. so are sin and cos)
- **1/(1 − x):** Σ xⁿ (1 + x + x² + ..., only for |x| < 1)
- **reach for it:** a repeating decimal as a fraction, a total of payments or bounces, why quicksort's average has an ln n in it, computing eˣ, sin x and cos x from a few terms, and knowing how many, the small-x shape of a function: sin x ≈ x

## the idea

a series is a sum that keeps going:

$$
a_1 + a_2 + a_3 + \cdots = \sum_{n=1}^{\infty} a_n
$$

nobody can add infinitely many numbers, so the definition goes through the partial sums: $S_1 = a_1$, $S_2 = a_1 + a_2$, and $S_n$ is the first $n$ terms added up. if $S_n$ closes in on a number as $n$ grows, the series converges and that number is its sum. if not, it diverges. take $1/2 + 1/4 + 1/8 + \cdots$. the partial sums are $1/2$, $3/4$, $7/8$, and $S_{10} = 1023/1024$: each term closes half of what's left, so they head for 1, and the sum is 1. "closes in on" is the limit from the limits page, $S = \lim_{n \to \infty} S_n$.

the second half of the page runs this backwards. start with a function, like $\sin x$ from the [trig](/math/trig/) page, and write it as a series of powers of $x$: $x - x^3/3! + x^5/5! - \cdots$. stop after a few terms and you have a polynomial that matches the function near 0, and a polynomial can be worked out with nothing but adding and multiplying. the movie adds the terms one at a time.

> **interactive figure:** an animation of the taylor polynomials of sin x at 0, drawn in white over sin x in cyan from −2π to 2π, with a band marking where the two agree within 0.01. the tangent line y = x matches out to |x| = 0.39. adding −x³/3! bends it onto the curve out to 1.04, x⁵/5! reaches 1.76, −x⁷/7! reaches 2.5 and x⁹/9! reaches 3.25. past its band each polynomial leaves the curve and flies off the chart.

$\sin x$ in cyan. the first polynomial is the tangent line at 0, $T_1(x) = x$: the same value and the same slope at the center, and the small-angle rule $\sin x \approx x$. it hugs the curve a short way, within 0.01 out to $|x| = 0.39$.

add $-x^3/3!$. the new term is 0 at the center and tiny near it, so nothing changes there. further out it bends the line down with the sine, and the match holds out to 1.04.

add $x^5/5!$: out to 1.76. the coefficients are the derivatives of $\sin$ at 0 divided by the factorials, and those derivatives read $0, 1, 0, -1, 0, 1, \ldots$ so only odd powers show up, with alternating signs.

add $-x^7/7!$: out to 2.5, over the hump at $\pi/2$ and down through $\pi$.

add $x^9/9!$: out to 3.25. a polynomial has to fly off eventually, and every one of these does, but each term pushes the good stretch further out. keep going and the series reaches every $x$: the factorials beat the powers.

## explore

pick a function and the number of terms. the function is cyan, the polynomial white, and the amber bar at the point is the gap between them. near 0 a few terms are enough; further out the gap grows and it takes more. for $1/(1 - x)$ and $\ln(1 + x)$ there's a line the series can't cross: past $|x| = 1$ the terms grow instead of shrinking, and more terms make the polynomial worse.

> **interactive figure:** an interactive chart: buttons pick eˣ, sin x, cos x, 1/(1 − x) or ln(1 + x), drawn in cyan, with its taylor polynomial at 0 drawn over it in white. a slider sets the number of terms from 1 to 10, and a point drags along the x axis, or moves with the arrow keys, reading the function, the polynomial, the gap between them in amber, the size of the first term left out, and how many terms it would take to get within 0.001 there. it opens on eˣ with four terms, 1 + x + x²/2! + x³/3!, at x = 1.5: the function is 4.4817, the polynomial 4.1875, the gap 0.294, and 8 terms would close it to 0.001. for 1/(1 − x) and ln(1 + x), dotted lines at x = −1 and x = 1 mark where the series converges; outside them the count reads never.

## try it

> **interactive figure:** a practice exercise with four kinds of question: whether a written-out series converges, the sum of a geometric series like 6 + 2 + 2/3 + ..., a repeating decimal like 0.272727... as a fraction, and the next term of a taylor series like sin x = x − x³/3! + x⁵/5! − .... it opens on 1/2 + 1/4 + 1/8 + 1/16 + ..., which is 1.

## the rules

### partial sums

$$
S_n = \sum_{k=1}^{n} a_k \qquad \sum_{n=1}^{\infty} a_n = \lim_{n \to \infty} S_n
$$

the sum of a series is the limit of its partial sums, when there is one. that's the whole definition: a series is a sequence of partial sums in disguise, and "converges" means that sequence settles. the figure draws the first 30 partial sums of four series. two of them close in on a line from below, one hops over its line and back with shrinking hops, and one climbs forever.

> **interactive figure:** an interactive chart of the first 30 partial sums of a series as points, with buttons for 1/2ⁿ, 1/n, (−1)ⁿ⁺¹/n and 1/n², and a slider that picks one sum to read out, starting at n = 10. 1/2 + 1/4 + ... closes in on a dashed line at 1: S₁₀ = 0.9990. 1 + 1/2 + 1/3 + ... climbs with no line, S₁₀ = 2.9290 and S₃₀ = 3.9950, tracking a dashed ln n + γ. 1 − 1/2 + 1/3 − ... hops over the dashed line at ln 2 ≈ 0.6931 and back: S₁₀ = 0.6456. 1 + 1/4 + 1/9 + ... closes in on π²/6 ≈ 1.6449 from below: S₁₀ = 1.5498, S₃₀ = 1.6122.

### a geometric series

$$
\begin{gathered}
a + ar + ar^2 + ar^3 + \cdots = \frac{a}{1 - r} \\[4pt]
\text{when } |r| < 1
\end{gathered}
$$

each term is the one before times $r$. the partial sum has a closed form, from subtracting $rS_n$ from $S_n$: everything cancels except the first term and the one past the last,

$$
\begin{gathered}
S_n - rS_n = a - ar^n \\[4pt]
S_n = \frac{a(1 - r^n)}{1 - r}
\end{gathered}
$$

when $|r| < 1$, $r^n$ shrinks to 0 and $S_n$ closes in on $a/(1 - r)$. when $|r| \ge 1$ the terms never shrink, and there is no sum. so $1/2 + 1/4 + 1/8 + \cdots = \frac{1/2}{1 - 1/2} = 1$, and a repeating decimal is a geometric series in disguise:

$$
\begin{aligned}
0.999\ldots &= \frac{9}{10} + \frac{9}{100} + \cdots \\[4pt]
&= \frac{9/10}{1 - 1/10} = 1
\end{aligned}
$$

not close to 1. equal to 1: the partial sums $0.9$, $0.99$, $0.999$ close in on 1 and on nothing else.

### terms that shrink aren't enough

$$
1 + \frac{1}{2} + \frac{1}{3} + \frac{1}{4} + \cdots = \infty
$$

for a series to converge its terms have to shrink to 0: if they didn't, the partial sums would keep moving by at least some fixed amount. the other direction fails. the terms of the harmonic series shrink to 0, and the sum still passes every number. group the terms in blocks that double in length:

$$
\begin{gathered}
\tfrac{1}{3} + \tfrac{1}{4} > \tfrac{1}{4} + \tfrac{1}{4} = \tfrac{1}{2} \\[4pt]
\tfrac{1}{5} + \tfrac{1}{6} + \tfrac{1}{7} + \tfrac{1}{8} > 4 \cdot \tfrac{1}{8} = \tfrac{1}{2} \\[4pt]
\tfrac{1}{9} + \cdots + \tfrac{1}{16} > 8 \cdot \tfrac{1}{16} = \tfrac{1}{2}
\end{gathered}
$$

every block of $2^k$ terms adds more than $1/2$, so $H_{2^k} \ge 1 + k/2$ and the sum grows without bound. slowly: it passes 2 at the 4th term, 5 at the 83rd and 10 at the 12,367th. the grouping only promises 10 by $2^{18} = 262{,}144$ terms, since it counts every term in a block as the block's smallest.

### how fast it grows

$$
\begin{aligned}
H_n &= 1 + \frac{1}{2} + \cdots + \frac{1}{n} \\[4pt]
&\approx \ln n + 0.5772
\end{aligned}
$$

$H_n$ is the $n$th harmonic number, and it grows like $\ln n$: the gap $H_n - \ln n$ settles at a constant, $\gamma \approx 0.5772$. an integral says why: each $1/k$ is a bar of width 1 sitting over the curve $1/x$, so $H_n$ is a little more than the area under $1/x$ from 1 to $n + 1$, and that area is $\ln(n + 1)$, the integral of $1/x$ from the integrals page. the estimate is good: $\ln 12{,}367 + 0.5772$ is 10.0000 on the nose, and it says the sum passes 20 at about $e^{20 - 0.5772}$ terms, 272 million. every extra 1 costs $e \approx 2.72$ times as many terms.

this sum is why quicksort's average has an $\ln n$ in it. sort $n$ distinct keys in random order, and the $i$th and $j$th smallest get compared only if the first pivot picked from the keys between them, both included, is one of the two: probability $2/(j - i + 1)$. add that over every pair and the harmonic numbers appear: $2(n + 1)H_n - 4n$ comparisons on average, 10,986 for $n = 1{,}000$, and about $2n \ln n$ for large $n$. that's the $2n \ln n$ on the [quicksort](/algos/quicksort/) page.

### a few that converge

$$
\begin{gathered}
\sum_{n=1}^{\infty} \frac{1}{n^p} \text{ converges when } p > 1 \\[6pt]
\sum_{n=1}^{\infty} \frac{1}{n^2} = \frac{\pi^2}{6} \approx 1.6449
\end{gathered}
$$

$1/n$ fails and $1/n^2$ works. the difference is a telescoping bound: $1/k^2 < 1/(k(k - 1)) = 1/(k - 1) - 1/k$ for $k \ge 2$, and those differences cancel in a chain, so the tail after $n$ terms is less than $1/n$ and the whole sum is less than 2. every $p \ge 2$ falls under the same bound. for $p$ between 1 and 2 the terms are bigger than $1/k^2$, so it takes a closer look, like the area under $1/x^p$, which is finite for every $p > 1$. for $p \le 1$ the terms are at least as big as $1/n$'s, which already run off. so $1/n^2$ and $1/n^3$ converge and $1/\sqrt{n}$ doesn't. the value $\pi^2/6$ takes more than this page. the partial sums reach 1.6350 at 100 terms and 1.6439 at 1,000, closing in at about $1/n$.

$$
\begin{aligned}
1 - \frac{1}{2} + \frac{1}{3} - \frac{1}{4} + \cdots &= \ln 2 \\[4pt]
&\approx 0.6931
\end{aligned}
$$

the harmonic series with alternating signs converges. the partial sums hop over the answer and back, each hop smaller than the last, so every partial sum is within the next term of the sum: $|S_n - \ln 2| < 1/(n + 1)$. that holds for any series whose terms alternate in sign and shrink to 0. it also makes this one slow: 1,000 terms give 0.6926, three digits. where $\ln 2$ comes from is below, with the taylor series.

### a taylor polynomial

$$
T_n(x) = \sum_{k=0}^{n} \frac{f^{(k)}(a)}{k!}\,(x - a)^k
$$

a polynomial built to agree with $f$ at $a$: the same value, the same slope, the same bend, and every derivative up to the $n$th. the coefficient of $(x - a)^k$ is the $k$th derivative at $a$ over $k!$, and the key idea below says why. $T_1$ is the tangent line from the derivatives page. let $n$ run on and you have the taylor series. the ones to know, all at $a = 0$:

$$
\begin{aligned}
e^x &= 1 + x + \tfrac{x^2}{2!} + \tfrac{x^3}{3!} + \cdots \\[4pt]
\sin x &= x - \tfrac{x^3}{3!} + \tfrac{x^5}{5!} - \cdots \\[4pt]
\cos x &= 1 - \tfrac{x^2}{2!} + \tfrac{x^4}{4!} - \cdots \\[4pt]
\tfrac{1}{1 - x} &= 1 + x + x^2 + x^3 + \cdots \\[4pt]
\ln(1 + x) &= x - \tfrac{x^2}{2} + \tfrac{x^3}{3} - \cdots
\end{aligned}
$$

the first three hold for every $x$. the first three also come from derivatives that repeat: every derivative of $e^x$ is $e^x$, which is 1 at 0, and the derivatives of $\sin$ cycle $\sin, \cos, -\sin, -\cos$, which at 0 read $0, 1, 0, -1$. the fourth is the geometric series with $r = x$, which is why it holds only for $|x| < 1$. the fifth holds for $-1 < x \le 1$: it's the fourth with $x$ replaced by $-x$, integrated term by term, and at $x = 1$ it's $1 - 1/2 + 1/3 - \cdots = \ln 2$, the alternating series from above, sitting right at the edge of where it works. the explore figure draws all five.

### how wrong is the polynomial

$$
\begin{gathered}
|f(x) - T_n(x)| \le \frac{M\,|x - a|^{n+1}}{(n + 1)!} \\[6pt]
\text{with } M \ge |f^{(n+1)}(t)| \\[2pt]
\text{for every } t \text{ between } a \text{ and } x
\end{gathered}
$$

the error of a taylor polynomial looks like the first term left out, with the derivative taken somewhere between $a$ and $x$ instead of at $a$. for $\sin$ and $\cos$ every derivative is at most 1, so $M = 1$ does. three terms of $\sin x$ at $x = 1$ are then off by at most $1/7! \approx 0.000198$, and the real gap is 0.000196. for $e^x$ at $x = 1$ take $M = 3$. two things follow. for a fixed $x$, $|x|^{n+1}/(n + 1)!$ heads to 0 however big $x$ is, because the factorial wins in the end, so the series for $e^x$, $\sin x$ and $\cos x$ work everywhere. and for a fixed $n$ the error grows like $|x - a|^{n+1}$, so far from the center you need many more terms: $\sin x$ to within a millionth takes 5 terms at $x = 1$, 8 at $x = \pi$ and 18 at $x = 10$.

## worked examples

### a repeating decimal

$0.272727\ldots$ is $27/100 + 27/10000 + \cdots$: geometric with $a = 27/100$ and $r = 1/100$,

$$
\frac{27/100}{1 - 1/100} = \frac{27}{99} = \frac{3}{11}
$$

check: $3 \div 11 = 0.2727\ldots$. with two repeating digits the denominator is 99, with one it's 9, so $0.333\ldots = 3/9 = 1/3$.

### how many terms to pass 10

the harmonic series passes 10 at the 12,367th term: $H_{12{,}366} = 9.99996$ and $H_{12{,}367} = 10.00004$. the estimate $n \approx e^{10 - 0.5772}$ gives 12,366.97, right on it. the grouping argument promises 10 only by $2^{18} = 262{,}144$ terms, twenty times later, because it counts each block of terms as if all of them were the smallest. to pass 5 it promises $2^8 = 256$ terms, where the real count is 83.

### sin 1 to six places

$\sin 1 = 0.841471$. the polynomials at $x = 1$, with the first term each one leaves out:

| terms | polynomial | at x = 1 | gap        | first term left out |
| ----- | ---------- | -------- | ---------- | ------------------- |
| 1     | x          | 1        | 0.159      | 1/3! = 0.167        |
| 2     | − x³/3!    | 0.8333   | 0.00814    | 1/5! = 0.00833      |
| 3     | + x⁵/5!    | 0.841667 | 0.000196   | 1/7! = 0.000198     |
| 4     | − x⁷/7!    | 0.841468 | 0.00000273 | 1/9! = 0.00000276   |

every gap sits just under the first term left out, as the error bound says, and the terms alternate, so the gap is smaller than that term. four terms get five places, and five terms get all six: $T_9(1) = 0.841471$, with a gap of $2.5 \times 10^{-8}$, under $1/11!$.

### e from its series

$e = \sum 1/n!$, the natural base from the [exponents + logs](/math/exponents-logs/) page. five terms, through $1/4!$, give $1 + 1 + 1/2 + 1/6 + 1/24 = 65/24 \approx 2.7083$, off by 0.00995 and under the bound $3/5! = 0.025$. ten terms give 2.7182815, off by $3.0 \times 10^{-7}$, and ten is the first count within a millionth. the factorials grow so fast that each term adds about a digit.

### ln 2, slowly and quickly

$\ln(1 + x)$ at $x = 1$ is $1 - 1/2 + 1/3 - \cdots$, and 1,000 terms give 0.6926 against $\ln 2 = 0.6931$: three digits, since the gap is about $1/2n$. the same series at $x = -1/2$ gives $\ln(1/2) = -\ln 2$, and its terms shrink like $1/2^n$: 10 terms are within 0.0000823, 20 within $4.35 \times 10^{-8}$. the edge of the interval is the slow place. inside it, the series is as fast as a geometric one.

### where 1/(1 − x) breaks

at $x = 1/2$ the series $1 + x + x^2 + \cdots$ is $1 + 1/2 + 1/4 + \cdots$, and 10 terms give 1.998 against the true 2. at $x = 2$ it's $1 + 2 + 4 + \cdots$: 10 terms give 1,023, 20 give 1,048,575, and the formula $1/(1 - 2) = -1$ has nothing to do with any of it. the formula is right for the function at every $x$ but 1, and the series is right only for $|x| < 1$. the two agree there and nowhere else.

## the key idea up close

### where the coefficients come from

suppose $f$ can be written as a power series around $a$, and ask what the coefficients have to be:

$$
\begin{gathered}
f(x) = c_0 + c_1 (x - a) \\
+ c_2 (x - a)^2 + c_3 (x - a)^3 + \cdots
\end{gathered}
$$

put $x = a$ and every term but the first vanishes: $f(a) = c_0$. differentiate once, which kills the constant and brings each power down by one:

$$
\begin{aligned}
f'(x) = c_1 &+ 2c_2 (x - a) \\
&+ 3c_3 (x - a)^2 + \cdots
\end{aligned}
$$

and at $x = a$, $f'(a) = c_1$. differentiate again: $f''(x) = 2c_2 + 3 \cdot 2\, c_3 (x - a) + \cdots$, so $f''(a) = 2c_2$. a third time, and $f'''(a) = 3 \cdot 2 \cdot 1\, c_3$. the $k$th derivative of $(x - a)^k$ is the constant $k!$. every lower power has been differentiated down to 0 by then, and every higher power still carries a factor of $(x - a)$, which is 0 at $a$. so

$$
f^{(k)}(a) = k!\, c_k \;\Rightarrow\; c_k = \frac{f^{(k)}(a)}{k!}
$$

that's the taylor formula, and it says the coefficients are forced: if any power series matches $f$ near $a$, it's this one. run it for $\sin$ at 0. the derivatives cycle $\sin, \cos, -\sin, -\cos$, so at 0 they read $0, 1, 0, -1, 0, 1, \ldots$ and the series is $x - x^3/3! + x^5/5! - \cdots$. for $e^x$ every derivative is 1 at 0, and the series is $\sum x^n/n!$. for $1/(1 - x)$ the $k$th derivative is $k!/(1 - x)^{k+1}$, which is $k!$ at 0, so every coefficient is 1 and the series is the geometric one, with its edge at $|x| = 1$. that's the reminder: matching every derivative at a point promises nothing about far away. the error bound above says how far the match holds, and the movie shows what it looks like.

## in code

`python/math/series.py` adds the series up term by term: the partial sums of the geometric, harmonic and alternating harmonic series, how many terms the harmonic series takes to pass a target, and the taylor polynomials of $e^x$ and $\sin x$ with the count of terms that gets within a tolerance at an $x$. its tests pin the numbers on this page: the sum passes 10 at 12,367 terms, ten terms of $\sum 1/n!$ are within $3.0 \times 10^{-7}$ of $e$, and $\sin x$ to a millionth takes 5 terms at $x = 1$ and 18 at $x = 10$.

the last function adds a million terms of $1/n$ three ways and gets three answers:

```text
forwards   14.392726722864989
backwards  14.392726722865772
math.fsum  14.392726722865724
```

the exact sum is 14.3927267228657236..., and the third answer is the double nearest it. forwards is off by $7.4 \times 10^{-13}$, backwards by $4.8 \times 10^{-14}$, fifteen times less. the mechanism is where the rounding happens. a double near 14 has a spacing of $1.8 \times 10^{-15}$, and the forward total is past 8 from the 1,674th term on, so almost every one of the million additions rounds at that spacing. summed backwards, the small terms are added while the total is still small and the spacing fine, and the big terms arrive last, when few additions are left. `math.fsum` tracks several partial sums as it goes and avoids the loss of precision.[^fsum]

the same thing bites a taylor polynomial far from its center. $e^{-20}$ by its series adds terms as big as 43 million that cancel down to $2.06 \times 10^{-9}$, and half the spacing of a double near 43 million is already $3.7 \times 10^{-9}$, so the answer comes out as $6.1 \times 10^{-9}$, three times too big. summing $e^{20}$ instead, where nothing cancels, and taking 1 over it agrees with `math.exp(-20)` to 15 digits.

`python/math/series.py`

```python
"""infinite series, summed term by term: the partial sums of the geometric, harmonic and alternating harmonic series, how many terms the harmonic series takes to pass a number, taylor polynomials for exp and sin and how many terms they need for a given accuracy at a given x, and one floating point fact: a million terms of 1/n give three different sums forwards, backwards and with math.fsum, and the order that adds the small terms first loses the least."""

from __future__ import annotations

import math
from collections.abc import Callable


def geometric_partial_sums(a: float, r: float, n: int) -> list[float]:
    """Return S_1 to S_n of a + ar + ar² + ..., adding one term at a time."""
    sums: list[float] = []
    total = 0.0
    term = a
    for _ in range(n):
        total += term
        sums.append(total)
        term *= r
    return sums


def geometric_sum(a: float, r: float) -> float:
    """Return a / (1 - r), what the partial sums of a + ar + ar² + ... close in on.

    Raise ValueError unless |r| < 1: otherwise the terms don't shrink to 0 and there is no sum.
    """
    if abs(r) >= 1:
        raise ValueError("a geometric series only adds up when |r| < 1")
    return a / (1 - r)


def harmonic(n: int) -> float:
    """Return H_n = 1 + 1/2 + ... + 1/n, added forwards."""
    total = 0.0
    for k in range(1, n + 1):
        total += 1 / k
    return total


def terms_to_pass(target: float) -> int:
    """Return the first n with H_n > target. H_n grows like ln n, so this is about e ** (target - 0.5772)."""
    total = 0.0
    n = 0
    while total <= target:
        n += 1
        total += 1 / n
    return n


def alternating_harmonic(n: int) -> float:
    """Return 1 - 1/2 + 1/3 - ... to n terms. It closes in on ln 2, and is always within 1/(n + 1) of it."""
    total = 0.0
    for k in range(1, n + 1):
        total += (1 if k % 2 else -1) / k
    return total


def exp_series(x: float, terms: int) -> float:
    """Return the taylor polynomial of e**x at 0 with the given number of terms: 1 + x + x²/2! + ...

    Each term is the one before times x/k, so no factorial is built.
    """
    total = 0.0
    term = 1.0
    for k in range(terms):
        total += term
        term *= x / (k + 1)
    return total


def sin_series(x: float, terms: int) -> float:
    """Return the taylor polynomial of sin x at 0 with the given number of terms: x - x³/3! + x⁵/5! - ...

    Each term is the one before times -x² / ((2k)(2k + 1)).
    """
    total = 0.0
    term = x
    for k in range(1, terms + 1):
        total += term
        term *= -x * x / ((2 * k) * (2 * k + 1))
    return total


def terms_needed(
    series: Callable[[float, int], float],
    f: Callable[[float], float],
    x: float,
    tol: float,
    limit: int = 200,
) -> int | None:
    """Return the fewest terms that bring series(x, terms) within tol of f(x), or None when limit terms don't."""
    target = f(x)
    for n in range(1, limit + 1):
        if abs(series(x, n) - target) < tol:
            return n
    return None


def harmonic_three_ways(n: int) -> tuple[float, float, float]:
    """Return H_n added forwards, added backwards, and added with math.fsum.

    Forwards, the running total is already near its final size while the small terms arrive, and every one of
    those additions rounds at that size. Backwards, the small terms add up among themselves first, while the
    total is still small, so each rounding is smaller. fsum tracks several partial sums as it goes and avoids
    the loss of precision.
    """
    forward = 0.0
    for k in range(1, n + 1):
        forward += 1 / k
    backward = 0.0
    for k in range(n, 0, -1):
        backward += 1 / k
    return forward, backward, math.fsum(1 / k for k in range(1, n + 1))
```

## pitfalls

- **terms going to 0 doesn't make a series converge.** $1/n \to 0$ and $1 + 1/2 + 1/3 + \cdots$ passes every number. the test only works the other way: terms that don't go to 0 rule a sum out
- **a taylor polynomial far from its center.** five terms of $\sin x$ are within 0.007 of $\sin \pi$ and off by 1,448 at $x = 10$. the error grows like $|x - a|^{n+1}$: add terms, move the center, or use a symmetry like $\sin(x - 2\pi k)$ to bring $x$ back near 0
- **$1/(1 - x) = 1 + x + x^2 + \cdots$ only for $|x| < 1$.** at $x = 2$ the right side is $1 + 2 + 4 + \cdots$ and the left side is $-1$. a series has a region where it converges, and a formula that's true there says nothing outside it
- **the order of a sum matters in floating point.** a million terms of $1/n$ give 14.392726722864989 forwards and 14.392726722865772 backwards. add the small terms first, or use `math.fsum`
- **the first term left out isn't always the error.** it's a bound when the terms alternate and shrink. for $e^x$ at $x = 1$ with five terms the gap is 0.00995 and the first term left out is $1/5! = 0.00833$, smaller than the gap
- **rearranging $1 - 1/2 + 1/3 - \cdots$ changes its sum.** take two positive terms for each negative one, and the same terms add up to $\tfrac{3}{2} \ln 2 \approx 1.0397$ instead of 0.6931. a series whose terms only add up because of their signs can be rearranged to any sum at all, so never reorder one

## practice

1. find $3 + \frac{3}{4} + \frac{3}{16} + \frac{3}{64} + \cdots$.

   **answer:** geometric with $a = 3$ and $r = 1/4$: $\frac{3}{1 - 1/4} = \frac{3}{3/4} = 4$. the partial sums agree: 3, 3.75, 3.9375, 3.984375, closing in on 4.

2. write $0.454545\ldots$ as a fraction.

   **answer:** $45/100 + 45/10000 + \cdots$ is geometric with $a = 45/100$ and $r = 1/100$: $\frac{45/100}{99/100} = \frac{45}{99} = \frac{5}{11}$. check: $5 \div 11 = 0.4545\ldots$

3. does each one converge? $\sum \frac{n}{n + 1}$, $\sum \frac{1}{\sqrt{n}}$, $\sum \frac{(-1)^{n+1}}{\sqrt{n}}$.

   **answer:** the first doesn't: the terms head to 1, not 0, so the partial sums grow by about 1 a step. the second doesn't either: $p = 1/2 \le 1$, and each $1/\sqrt{n}$ is at least $1/n$, which already run off. the third does: the terms alternate and shrink to 0, so the partial sums hop over the sum and back with shrinking hops. it adds up only because of the signs, which is what makes reordering it dangerous.

4. use the grouping argument to show $H_{2^k} \ge 1 + k/2$, say how many terms it guarantees for the sum to pass 5, and compare with the real count, 83.

   **answer:** the block from $1/(2^j + 1)$ to $1/2^{j+1}$ has $2^j$ terms, each at least $1/2^{j+1}$, so it adds at least $1/2$. $H_{2^k}$ is 1 plus $k$ such blocks, so at least $1 + k/2$. to reach 5 take $k = 8$: $2^8 = 256$ terms, where $H_{256} \approx 6.12$. the real crossing is at 83 terms, since each block is worth more than $1/2$. the bound is loose, but it proves the point: the sum has no ceiling.

5. write the degree 4 taylor polynomial of $e^x$ at 0, evaluate it at $x = 1$, and bound the error.

   **answer:** every derivative is 1 at 0, so $T_4(x) = 1 + x + \frac{x^2}{2} + \frac{x^3}{6} + \frac{x^4}{24}$. at $x = 1$: $1 + 1 + \frac{1}{2} + \frac{1}{6} + \frac{1}{24} = \frac{65}{24} \approx 2.7083$. the error is at most $M/5!$ with $M$ a bound on $e^t$ for $t$ between 0 and 1, and $e < 3$ gives $3/120 = 0.025$. the real gap is $e - 2.7083 = 0.0099$.

6. how many terms of $\sin x = x - x^3/3! + \cdots$ get $\sin 2$ to within $10^{-4}$?

   **answer:** the terms alternate and shrink, so the gap is under the first term left out. $2^9/9! = 0.00141$ isn't small enough and $2^{11}/11! = 0.0000513$ is, so keep through $x^9/9!$: five terms, degree 9. check: $T_9(2) = 0.909347$ against $\sin 2 = 0.909297$, a gap of 0.00005.

[^fsum]: python's [math](https://docs.python.org/3/library/math.html#math.fsum) docs: `math.fsum` returns an accurate floating-point sum of the values in an iterable, and avoids the loss of precision by tracking multiple intermediate partial sums.

## related

- https://learning.anthnydas.com/math/limits.md
- https://learning.anthnydas.com/math/derivatives.md
- https://learning.anthnydas.com/math/integrals.md
- https://learning.anthnydas.com/math/exponents-logs.md
- https://learning.anthnydas.com/math/trig.md
- https://learning.anthnydas.com/algos/quicksort.md
