---
title: "Lab: Taylor polynomials in code"
heading: How many terms, and how to keep the count small
eyebrow: A6 · Lesson 38 · Lab: Taylor polynomials in code
xp: 60
---

::: hook
A Taylor polynomial is only as good as its error bound, and the bound depends brutally on how far from the center you evaluate it. $\sin x$ to twelve digits needs degree 13 at $x = \pi/4$ but degree 23 at $x = 3$, and at $x = 100$ the terms would grow to $10^{42}$ before shrinking. In this lab you'll compute Taylor polynomials, compare their actual errors with the Lagrange bounds, count the terms each accuracy needs, and use range reduction to evaluate $\sin$ anywhere with a short polynomial.
:::

::: play
- The curve is $|\sin x - P_n(x)|$, the error of the degree-$n$ Taylor polynomial about 0, on a log scale.
- The error is tiny near 0 and grows rapidly with $|x|$. Raise $n$ and the region where it's below $10^{-12}$ widens, slowly.
- Range reduction keeps $|x| \le \pi/4$, the shaded strip, where degree 13 is already enough.
:::

```sim plot
view: graph
x: x = 0..6
y: err = 1e-16..10 log
slider: n = 1..21 step 2 = 9
plot: abs(x)^(n + 2)/(n + 2)! | samples: 300 | label: Lagrange bound, degree n
marker: x = pi/4 | label: π/4
marker: err = 1e-12 | label: 10⁻¹²
```

::: predict
## The degree-9 Taylor polynomial for $\sin x$ about 0 is used at $x = 1$. Its Lagrange bound is $\frac{|x|^{11}}{11!}$. About how accurate is it?

- [ ] About $10^{-3}$
- [ ] About $10^{-5}$
- [x] About $2.5 \times 10^{-8}$
- [ ] Exact

::: reveal
About $2.5 \times 10^{-8}$: $\frac{1}{11!} = 2.5 \times 10^{-8}$. At $x = 0.5$ the same polynomial is good to $1.2 \times 10^{-11}$, and at $x = 3$ only to $4.4 \times 10^{-3}$. The bound grows like $|x|^{11}$, which is why libraries reduce the argument first.
:::
:::

::: nameit
## Errors you can bound

For $e^x$, $\sin x$ and $\cos x$ the derivatives are bounded nicely:
- $\sin$ and $\cos$: every derivative is at most 1, so the degree-$n$ error is at most $\frac{|x|^{n+1}}{(n + 1)!}$ (and for $\sin$'s odd polynomials, $\frac{|x|^{n+2}}{(n + 2)!}$);
- $e^x$ on $[0, x]$: at most $\frac{e^x x^{n+1}}{(n + 1)!}$.

Comparing the actual error with the bound shows how pessimistic the bound is: usually within a small factor.

## Counting terms

To meet a tolerance, raise the degree until the bound falls below it. Doing this in a loop gives the degree directly, with no guesswork.

## Range reduction

$\sin$ has period $2\pi$ and symmetries that reduce any $x$ to $r = x - k\frac{\pi}{2}$ with $|r| \le \frac{\pi}{4}$:

$$\sin x = \begin{cases}\sin r & k \equiv 0 \\ \cos r & k \equiv 1 \\ -\sin r & k \equiv 2 \\ -\cos r & k \equiv 3\end{cases} \pmod 4$$

On $|r| \le \pi/4$, polynomials of degree 11 and 10 for $\sin$ and $\cos$ reach about $10^{-13}$.
:::

::: example
## How many terms of $e^x$'s series give $e$ to within $10^{-6}$, by the Lagrange bound?

::: solution
1. **Write the bound.** The bound after degree $n$ is $\frac{e}{(n + 1)!}$.
2. **Try degrees 6 to 9.**
   $$\begin{aligned} n = 6&: \quad 5.4 \times 10^{-4} \\ n = 7&: \quad 6.7 \times 10^{-5} \\ n = 8&: \quad 7.5 \times 10^{-6} \\ n = 9&: \quad 7.5 \times 10^{-7} \end{aligned}$$
   So degree 9, ten terms.
3. **Check the actual error.** The actual error at degree 6 is $2.3 \times 10^{-4}$, about 40% of the bound.

**Answer:** degree 9, which is ten terms.
:::
:::

::: example
## Evaluate $\sin 10$ with range reduction.

::: solution
1. **Count quarter turns.**
   $$\frac{10}{\pi/2} = 6.37$$
   so $k = 6$.
2. **Find the remainder.**
   $$\begin{aligned} r &= 10 - 6 \times \frac\pi2 \\ &= 0.575\,22 \end{aligned}$$
3. **Fix the sign.** Since $k \equiv 2 \pmod 4$:
   $$\begin{aligned} \sin 10 &= -\sin r \\ &= -0.544\,02 \end{aligned}$$
4. **See why it pays.** A degree-11 polynomial at $r = 0.575$ is accurate to about $10^{-13}$, while the same polynomial at $x = 10$ directly would be off by thousands.

**Answer:** $\sin 10 = -0.544\,02$.
:::
:::

::: check
given: x = 0.5 | 1 | 2; n = 5 | 9
answer: x^(n + 2)/(n + 2)!
tolerance: 0.5%

## What is the Lagrange bound for $\sin x \approx P_{\given{n}}(x)$ (odd degree {n}) at $x$ = {x}?

::: right
Right. $\frac{|x|^{n+2}}{(n + 2)!}$ = {answer}.
:::

::: misses
- [x^(n + 1)/(n + 1)!] For $\sin$'s odd polynomial, the next term is degree $n + 2$, so the bound is $\frac{|x|^{n+2}}{(n + 2)!}$.
- [any] Not yet. The first omitted term of $\sin$'s series bounds the error.
:::
:::

::: check
given: x = 3 | 7 | 10
answer: x - round(x/(pi/2))*pi/2
tolerance: 0.5%

## Range reduction subtracts the nearest multiple of $\pi/2$ from $x$ = {x}. What is left?

::: right
Right. $r$ = {answer}, within $\pm\pi/4$.
:::

::: misses
- [any] Not yet. $r = x - k\frac\pi2$ with $k$ = round($x/(\pi/2)$).
:::
:::

::: check
kind: python

## Write `taylor_exp(x, n)` (the degree-$n$ Taylor polynomial of $e^x$ about 0) and `exp_bound(x, n)` $= \frac{e^xx^{n+1}}{(n + 1)!}$ for $x > 0$. Set `deg` to the smallest $n$ whose bound at $x = 1$ is below $10^{-6}$.

```python starter
import math

def taylor_exp(x, n):
    return 1 + x

def exp_bound(x, n):
    return 0

deg = 0
print(deg)
```

```python solution
import math

def taylor_exp(x, n):
    return sum(x**k / math.factorial(k) for k in range(n + 1))

def exp_bound(x, n):
    return math.exp(x) * x**(n + 1) / math.factorial(n + 1)

deg = 0
while exp_bound(1, deg) >= 1e-6:
    deg += 1
print(deg)
```

```python tests
import math
assert deg == 9, f"Degree 9 is the first whose bound at x = 1 is below 1e-6; got {deg}."
for n in (3, 6, 9):
    assert abs(taylor_exp(1, n) - math.e) <= exp_bound(1, n), f"The actual error must be within the bound at degree {n}."
assert abs(taylor_exp(0.5, 6) - math.exp(0.5)) < 2e-6, "Degree 6 at x = 0.5 should be within 2e-6."
```

::: right
Right. The bound is honest: the true error at degree 6 is 40% of it, never more.
:::
:::

::: check
kind: python

## Write `sin_degree(x, tol)` returning the smallest odd degree $n$ with $\frac{|x|^{n+2}}{(n + 2)!} <$ `tol`. Set `d1`, `d2`, `d3` for $x$ = 0.5, $\pi/4$ and 3, all with tol = $10^{-12}$.

```python starter
import math

def sin_degree(x, tol):
    return 1

d1, d2, d3 = sin_degree(0.5, 1e-12), sin_degree(math.pi / 4, 1e-12), sin_degree(3, 1e-12)
print(d1, d2, d3)
```

```python solution
import math

def sin_degree(x, tol):
    n = 1
    while abs(x) ** (n + 2) / math.factorial(n + 2) >= tol:
        n += 2
    return n

d1, d2, d3 = sin_degree(0.5, 1e-12), sin_degree(math.pi / 4, 1e-12), sin_degree(3, 1e-12)
print(d1, d2, d3)
```

```python tests
assert (d1, d2, d3) == (11, 13, 23), f"The degrees should be 11, 13 and 23; got {(d1, d2, d3)}."
assert sin_degree(0.1, 1e-6) == 3, "Near 0, degree 3 is plenty for 1e-6."
```

::: right
Right. Going from $\pi/4$ to 3 nearly doubles the degree, which is the cost range reduction avoids.
:::
:::

::: check
kind: python
given: x = 10 | 100 | 1000.5

## Write `sin_reduced(x)`: reduce $x$ to $r = x - k\frac\pi2$ with $k$ = `round(x / (math.pi / 2))`, then return $\pm\sin r$ or $\pm\cos r$ by $k \bmod 4$, using degree-11 and degree-10 Taylor polynomials. Set `s = sin_reduced(x)` for $x$ = {x}.

```python starter
import math

def sin_reduced(x):
    return x - x**3 / 6

s = sin_reduced(x)
print(s, math.sin(x))
```

```python solution
import math

def sin_reduced(x):
    k = round(x / (math.pi / 2))
    r = x - k * math.pi / 2
    sp = sum((-1)**i * r**(2 * i + 1) / math.factorial(2 * i + 1) for i in range(6))
    cp = sum((-1)**i * r**(2 * i) / math.factorial(2 * i) for i in range(6))
    return [sp, cp, -sp, -cp][k % 4]

s = sin_reduced(x)
print(s, math.sin(x))
```

```python tests
import math
assert abs(s - math.sin(x)) < 1e-10, f"sin({x}) should match math.sin to 1e-10; got {s} against {math.sin(x)}."
for v in (0.3, 2.0, -5.0, 50.0):
    assert abs(sin_reduced(v) - math.sin(v)) < 1e-10, f"sin_reduced({v}) should match math.sin."
```

::: right
Right. Two short polynomials and a reduction step give $\sin$ anywhere, which is close to how a math library does it.
:::
:::

::: check
kind: python

## Compare the actual error with the bound. For $\sin$'s degree-9 polynomial, set `ratios` to the list of actual error divided by the bound $\frac{|x|^{11}}{11!}$ at $x$ = 0.5, 1, 2 and 3.

```python starter
import math

ratios = []
print(ratios)
```

```python solution
import math

def p9(x):
    return sum((-1)**i * x**(2 * i + 1) / math.factorial(2 * i + 1) for i in range(5))

ratios = [abs(math.sin(x) - p9(x)) / (x**11 / math.factorial(11)) for x in (0.5, 1, 2, 3)]
print(ratios)
```

```python tests
assert len(ratios) == 4 and all(0 < r <= 1 for r in ratios), f"The actual error must lie within the bound; got {ratios}."
assert ratios[0] > 0.99, "For small x the bound is almost exact: the next term dominates."
assert ratios[-1] < ratios[0], "Farther out, the bound is more pessimistic."
```

::: right
Right. For small $x$ the first omitted term is nearly the whole error; farther out the bound overestimates, but never underestimates.
:::
:::

::: check
kind: python

## Reduce for $e^x$ too: write `exp_reduced(x)`, which sets $k$ = `round(x / math.log(2))` and $r = x - k\ln 2$ (so $|r| \le \frac{\ln 2}{2}$), then returns $2^k$ times the degree-12 Taylor polynomial at $r$. Check its relative error against `math.exp` from $-20$ to 20.

```python starter
import math

def exp_reduced(x):
    return sum(x**i / math.factorial(i) for i in range(13))

print(exp_reduced(20), math.exp(20))
```

```python solution
import math

def exp_reduced(x):
    k = round(x / math.log(2))
    r = x - k * math.log(2)
    return 2.0**k * sum(r**i / math.factorial(i) for i in range(13))

print(exp_reduced(20), math.exp(20))
```

```python tests
import math
for x in (-20, -3.3, 0.7, 5, 20):
    assert abs(exp_reduced(x) - math.exp(x)) / math.exp(x) < 1e-14, f"exp_reduced({x}) should match math.exp to 1e-14 relative."
```

::: right
Right. Multiplying by a power of 2 is exact in binary, so all the error is in a short polynomial on a tiny interval.
:::
:::

::: explain
## Why does range reduction cut the work so much more than adding terms would?

::: model
A Taylor polynomial's error goes like $\frac{|x|^{n+1}}{(n + 1)!}$: the power of $|x|$ grows with the degree, and only the factorial eventually wins. Far from the center, the terms first grow huge before the factorial takes over, so a large degree is needed, and the cancellation among big terms of alternating sign costs digits in floating point too. Range reduction attacks the base instead of the exponent: bringing $|x|$ down below $\pi/4$ makes every term small from the start, so a fixed short polynomial is accurate everywhere, and there's no cancellation to lose digits to. Adding terms fights the problem; reducing the argument removes it.
:::
:::

::: practice

::: check
given: x = 0.1..3; n = 1..15 int
answer: x^(2*n + 3)/(2*n + 3)!
tolerance: 0.5%

## Bound for $\sin$'s odd polynomial of degree $2\cdot\given{n} + 1$ at $x$ = {x}?

::: misses
- [any] $\frac{|x|^{2n+3}}{(2n + 3)!}$.
:::
:::

::: check
given: x = 1..100
answer: x - round(x/(pi/2))*pi/2
tolerance: 0.5%

## Range-reduce {x} by multiples of $\pi/2$?

::: misses
- [any] $x - k\frac\pi2$, $k$ = round($2x/\pi$).
:::
:::
:::
