---
title: Computing functions from series in Python
heading: How a math library computes exp and sin
eyebrow: A6 · Lesson 45 · Series in code
xp: 50
---

::: hook
When you call `math.exp(x)`, something has to turn $x$ into a number, using only additions and multiplications. A Taylor series looks like the obvious answer: add terms until they're too small to matter. It mostly works, and in this lab you'll write it. But try it on $e^{-20}$ and you get an answer three times too big, with every digit wrong. Floating-point arithmetic has only about 16 significant digits, and an alternating series with huge terms throws them away. Knowing when a series is safe to use in code is as important as knowing that it converges.
:::

::: play
- The curve shows the size of each term $\frac{x^n}{n!}$ of the series for $e^x$, on a log scale (each unit up is a factor of 10).
- The terms grow until $n \approx x$, then fall. For $e^{-x}$ the same terms appear with alternating signs, and they must cancel down to the tiny answer $e^{-x}$.
- The readout estimates how many of the 16 available digits that cancellation destroys. At what $x$ does it pass 16?
:::
:::

```sim plot
view: graph
x: n = 0..60
y: size = -15..15
slider: x0 = 1..25 step 1 = 10
plot: log(x0^floor(n)/floor(n)!) | label: log₁₀ of xⁿ/n! | samples: 1200
plot: log(exp(-x0)) | label: log₁₀ of e⁻ˣ | color: ch3
readout: largest term = x0^floor(x0)/floor(x0)! | digits: 4
readout: digits lost computing e^-x = log(x0^floor(x0)/floor(x0)!/exp(-x0)) | digits: 3
```

::: predict
## You sum the series for $e^{-20}$ directly, $1 - 20 + \frac{20^2}{2!} - \cdots$, in double precision. What happens?

- [ ] It gives $e^{-20}$ to about 16 digits
- [ ] It takes too many terms but is accurate
- [x] The answer is wrong in every digit
- [ ] It never stops

::: reveal
Every digit is wrong. The largest terms are about $4 \times 10^7$, and they have to cancel down to $e^{-20} = 2 \times 10^{-9}$, sixteen orders of magnitude smaller. Each term carries a rounding error near $10^{-16}$ of its size, about $10^{-9}$, as big as the answer itself. The fix is simple: compute $e^{20}$, whose terms are all positive, and take $1/e^{20}$.
:::
:::

::: nameit
## Summing a series in code

Two habits make a series loop fast and correct:

1. **Build each term from the last.** For $e^x$, the next term is the previous one times $\frac{x}{n}$. Computing $x^n$ and $n!$ separately is slower and overflows for large $n$.
2. **Stop on a relative tolerance.** Stop when the term is smaller than about $10^{-16}$ times the running total. A fixed absolute tolerance is wrong for big answers and for small ones.

```python
def exp_series(x, tol=1e-16):
    total, term, n = 1.0, 1.0, 0
    while abs(term) > tol * abs(total):
        n += 1
        term *= x / n
        total += term
    return total, n
```

## Cancellation

Floating-point numbers carry about 16 significant digits. Subtracting nearly equal numbers keeps their absolute error but makes the result small, so its relative error grows. In an alternating series, if the largest term is $10^k$ times the final answer, about $k$ digits are lost. For $e^{-x}$ with large $x$ that's catastrophic; for the series of $\sin x$ with large $x$ it's just as bad.

## Range reduction

Libraries avoid large arguments altogether:

- **sin and cos:** subtract the nearest multiple of $2\pi$ (and use symmetries to get within $\pm\frac{\pi}{4}$). Python's `math.remainder(x, 2*math.pi)` gives a value in $[-\pi, \pi]$.
- **exp:** compute $e^{-x}$ as $1/e^{x}$, and for large $x$ write $x = k\ln 2 + r$ with $|r| \le \frac{\ln 2}{2}$, so $e^x = 2^ke^r$ and the series only ever sees a small $r$.

After range reduction a dozen terms suffice, and a fixed polynomial with tuned coefficients replaces the open-ended loop. That's what the C library actually ships.
:::

::: example
## About how many digits are lost computing $e^{-10}$ from its alternating series?

::: solution
1. **Find the largest term.** It's near $n = 10$:
   $$\frac{10^{10}}{10!} = 2756$$
2. **Compare it with the answer.** The answer is $e^{-10} = 4.54 \times 10^{-5}$, so the ratio is $6.1 \times 10^7$.
3. **Count the digits lost.**
   $$\log_{10}(6.1 \times 10^7) = 7.8$$
   so about 7.8 digits are lost, leaving about 8 good ones.
4. **Try $x = 20$.** There the loss is 16.3 digits, which is all of them.

**Answer:** about 7.8 digits are lost, leaving about 8 good ones.
:::
:::

::: example
## How many terms does `exp_series` take at $x = 1$, $x = 5$ and $x = 20$?

::: solution
1. **Run the loop.** It gives 18, 33 and 67.
2. **See why large arguments are slow.** The loop must pass the peak term near $n = x$ and then wait for the factorial to bring the terms down by 16 orders of magnitude, so large arguments are slow as well as risky.
3. **Reduce the range.** With range reduction to $|r| \le 0.35$, 14 terms always suffice.

**Answer:** 18 terms at $x = 1$, 33 at $x = 5$ and 67 at $x = 20$.
:::
:::

::: check
kind: python
given: x = 0.5 | 2 | 5

## Write `exp_series(x)` returning `(total, n)`: the sum of the series for $e^x$, built term by term, stopping when the term is below `1e-16` times the total; `n` is the number of terms added after the first. The test uses $x$ = {x}.

```python starter
import math

def exp_series(x, tol=1e-16):
    total, n = 0.0, 0
    # build each term from the last: term *= x / n
    return total, n

print(exp_series(x), math.exp(x))
```

```python solution
import math

def exp_series(x, tol=1e-16):
    total, term, n = 1.0, 1.0, 0
    while abs(term) > tol * abs(total):
        n += 1
        term *= x / n
        total += term
    return total, n

print(exp_series(x), math.exp(x))
```

```python tests
import math
v, n = exp_series(0.0)
assert v == 1.0, "e⁰ = 1: start the total at the first term, 1."
v, n = exp_series(x)
assert abs(v - math.exp(x)) <= 4e-16 * math.exp(x), f"exp_series({x}) gave {v}, but e^{x} = {math.exp(x)}."
assert 5 < n < 60, f"It took {n} terms; check the stopping rule."
v1, n1 = exp_series(1.0)
assert abs(v1 - math.e) < 1e-15, "exp_series(1) should be e to full precision."
```

::: right
Right. With a relative stopping rule, the sum is as accurate as double precision allows.
:::
:::

::: check
kind: python
given: k = 0 | 1 | 2

## Write `sin_series(x)` that first reduces $x$ into $[-\pi, \pi]$ with `math.remainder(x, 2*math.pi)`, then sums $x - \frac{x^3}{3!} + \cdots$ until the term is below `1e-17` in size. The tests try large arguments.

```python starter
import math

def sin_series(x):
    total = 0.0
    # reduce x, then add terms: each is the last times -x*x/((n+1)*(n+2))
    return total

print(sin_series(100.0), math.sin(100.0))
```

```python solution
import math

def sin_series(x):
    x = math.remainder(x, 2 * math.pi)
    total, term, n = x, x, 1
    while abs(term) > 1e-17:
        term *= -x * x / ((n + 1) * (n + 2))
        n += 2
        total += term
    return total

print(sin_series(100.0), math.sin(100.0))
```

```python tests
import math
for t in (0.3, 3.0, -2.5, 100.0 + k, -50.5 - k, 1000.0 + k):
    got = sin_series(t)
    assert abs(got - math.sin(t)) < 1e-12, f"sin_series({t}) gave {got}; math.sin gives {math.sin(t)}. Did you reduce x first?"
```

::: right
Right. After range reduction the series never sees an argument bigger than π, so it needs at most about 20 terms and stays accurate.
:::
:::

::: check
given: x = 10 | 20 | 15
answer: log(x^x/x!*exp(x))
tolerance: 1%

## About how many decimal digits are lost computing $e^{-\given{x}}$ from its alternating series? (Largest term divided by the answer, as a power of ten.)

::: right
Right. The largest terms are bigger than the answer by about {answer} powers of ten, so that many digits are lost.
:::

::: misses
- [log(x^x/x!)] Divide by the answer, $e^{-x}$, too: what matters is how much bigger the terms are than the result.
- [any] Not yet. $\log_{10}\left(\frac{x^x}{x!} \div e^{-x}\right)$.
:::
:::

::: check
given: x = 10 | 13 | 16
answer: x - 2*pi*round(x/(2*pi))
tolerance: 0.01%

## What does `math.remainder(x, 2*math.pi)` return for $x$ = {x}?

::: right
Right. It subtracts the nearest multiple of $2\pi$, leaving {answer}, inside $[-\pi, \pi]$.
:::

::: misses
- [x - 2*pi] Subtract the nearest multiple of $2\pi$, which may not be one.
- [any] Not yet. $x - 2\pi \times \text{round}(x/2\pi)$.
:::
:::

::: check
kind: choice

## Why does a math library reduce the argument before summing a series?

- [x] Small arguments need few terms and avoid cancellation
- [ ] The series only converges for small arguments
- [ ] Large arguments overflow the factorial
- [ ] To make the function periodic

::: right
Right. The series for $e^x$ and $\sin x$ converge for every $x$, but a large argument means many terms and, for alternating series, huge terms cancelling.
:::

::: misses
- [2] These series converge everywhere. The trouble is speed and rounding.
- [3] Building each term from the last avoids computing $n!$ at all.
- [any] Think about how many terms, and how big they get.
:::
:::

::: check
kind: python

## Write `ln1p(x, tol=1e-12)` returning `(value, terms)` for $\ln(1 + x) = x - \frac{x^2}{2} + \frac{x^3}{3} - \cdots$, stopping when a term's size is below `tol`. Compare the term counts at $x$ = 0.1 and 0.9.

```python starter
import math

def ln1p(x, tol=1e-12):
    return x, 1

print(ln1p(0.1), ln1p(0.9))
```

```python solution
import math

def ln1p(x, tol=1e-12):
    total, n, power = 0.0, 1, x
    while abs(power / n) >= tol:
        total += power / n if n % 2 else -power / n
        n += 1
        power *= x
    return total, n - 1

print(ln1p(0.1), ln1p(0.9))
```

```python tests
import math
v, n = ln1p(0.1)
assert abs(v - math.log(1.1)) < 1e-12 and n == 10, f"At 0.1 it takes 10 terms; got {n}."
v, n = ln1p(0.9)
assert abs(v - math.log(1.9)) < 1e-11 and n == 211, f"At 0.9 it takes 211 terms; got {n}."
```

::: right
Right. Ten terms near 0, two hundred near 1: this series needs its argument reduced too.
:::
:::

::: explain
## Why does summing the series for $e^{-20}$ directly give a wrong answer, while $1/e^{20}$ is accurate?

::: model
The series for $e^{-20}$ alternates, and its terms grow to about $4 \times 10^7$ before shrinking. To land on the true value, $2 \times 10^{-9}$, those huge terms must cancel almost perfectly. Each one carries a rounding error of about one part in $10^{16}$ of its size, around $10^{-9}$, which is as large as the answer, so the result is noise. The series for $e^{20}$ has only positive terms, so nothing cancels and every digit is good; dividing 1 by it keeps that accuracy.
:::
:::

::: practice

::: check
kind: python
given: x = 20 | 22 | 25 | 28 | 30

## Set `direct` to $e^{-x}$ summed straight from the series at $-x$ (use `exp_series`), and `better` to `1 / exp_series(x)[0]`, with $x$ = {x}. The tests check which one is right.

```python starter
import math

def exp_series(x, tol=1e-16):
    total, term, n = 1.0, 1.0, 0
    while abs(term) > tol * abs(total):
        n += 1
        term *= x / n
        total += term
    return total, n

direct = 0.0
better = 0.0
print(direct, better, math.exp(-x))
```

```python solution
import math

def exp_series(x, tol=1e-16):
    total, term, n = 1.0, 1.0, 0
    while abs(term) > tol * abs(total):
        n += 1
        term *= x / n
        total += term
    return total, n

direct = exp_series(-x)[0]
better = 1 / exp_series(x)[0]
print(direct, better, math.exp(-x))
```

```python tests
import math
assert abs(better - math.exp(-x)) < 1e-14 * math.exp(-x), "better should match math.exp(-x) to full precision."
assert abs(direct - math.exp(-x)) > 0.5 * math.exp(-x), "direct should be the series summed at -x, which cancellation ruins."
```
:::

::: check
given: x = 3..12 int
answer: log(x^x/x!*exp(x))
tolerance: 1%

## About how many decimal digits are lost computing $e^{-\given{x}}$ from its alternating series?

::: misses
- [log(x^x/x!)] Divide by the answer, $e^{-x}$, too.
- [any] $\log_{10}$ of the largest term divided by $e^{-x}$.
:::
:::
:::
