Taylor and Maclaurin Series
A Taylor series rebuilds a function from its derivatives at a single point. Cut it off after a few terms and you get a polynomial that imitates the function near that point. This is how calculators and math libraries compute sin, exp and log, and why physicists may replace by for small angles.
The formula
If has derivatives of every order at , its Taylor series at is
With it is called a Maclaurin series. The first two terms are the tangent line from The Derivative; each further term matches one more derivative, so the polynomial hugs the curve more and more closely.
The coefficient rule is easy to see: differentiate times and set ; only survives, so .
The series to know
| Function | Maclaurin series | Valid for |
|---|---|---|
| all | ||
| all | ||
| all | ||
Derivation of the sine row: the derivatives of at 0 cycle , so only odd powers appear, with alternating signs.
import sympy as sp
x = sp.symbols("x")
for f in [sp.exp(x), sp.sin(x), sp.cos(x), sp.log(1 + x)]:
print(f"{str(f):10}", sp.series(f, x, 0, 6))
h = sp.symbols("h") # x = 1 + h, a step away from 1
print("sqrt(1 + h):", sp.series(sp.sqrt(1 + h), h, 0, 3))exp(x) 1 + x + x**2/2 + x**3/6 + x**4/24 + x**5/120 + O(x**6)
sin(x) x - x**3/6 + x**5/120 + O(x**6)
cos(x) 1 - x**2/2 + x**4/24 + O(x**6)
log(x + 1) x - x**2/2 + x**3/3 - x**4/4 + x**5/5 + O(x**6)
sqrt(1 + h): 1 + h/2 - h**2/8 + O(h**3)
O(x**6) stands for "terms of order and higher, left out". The last line is the Taylor series of centred at , written with : .
Watching the polynomials hug the curve
import math
import numpy as np
import matplotlib.pyplot as plt
xs = np.linspace(-2 * np.pi, 2 * np.pi, 400)
def taylor_sin(x, degree):
return sum((-1) ** k * x ** (2 * k + 1) / math.factorial(2 * k + 1)
for k in range(degree // 2 + 1))
plt.figure(figsize=(6, 4))
plt.plot(xs, np.sin(xs), color="black", linewidth=2, label="sin x")
for d in [1, 3, 5, 7]:
plt.plot(xs, taylor_sin(xs, d), label=f"degree {d}")
plt.ylim(-3, 3)
plt.legend(loc="lower left")
print("at x = 2: ", [round(taylor_sin(2, d), 4) for d in (1, 3, 5, 7)], "sin 2 =", round(math.sin(2), 4))at x = 2: [2.0, 0.6667, 0.9333, 0.9079] sin 2 = 0.9093
Each extra term widens the region where the polynomial is a good copy of , but far from 0 every polynomial eventually shoots off.
In software: how math.exp and math.sin are computed
Library functions do not sum a long Taylor series for large ; that would be slow and inaccurate. Instead they:
- Reduce the range: write with , so . Multiplying by is just adjusting the floating-point exponent. For , subtract multiples of and use symmetries.
- Approximate on the small range with a short polynomial. Real libraries use minimax polynomials, close cousins of the Taylor polynomial whose coefficients are tuned to spread the error evenly, but a Taylor polynomial shows the idea.
import math
LN2 = math.log(2)
def my_exp(x, terms=12):
k = round(x / LN2) # step 1: x = k·ln2 + r
r = x - k * LN2
p = 0.0
for n in reversed(range(terms)): # step 2: Taylor polynomial (Horner form)
p = p * r + 1 / math.factorial(n)
return math.ldexp(p, k) # p · 2^k
for x in [0.3, 1.0, 10.0, -20.0, 300.0]:
mine, ref = my_exp(x), math.exp(x)
print(f"x={x:6}: my_exp = {mine:.15e} relative error {abs(mine - ref) / ref:.1e}")x= 0.3: my_exp = 1.349858807576002e+00 relative error 9.9e-16
x= 1.0: my_exp = 2.718281828459042e+00 relative error 9.8e-16
x= 10.0: my_exp = 2.202646579480671e+04 relative error 3.3e-16
x= -20.0: my_exp = 2.061153622438560e-09 relative error 8.0e-16
x= 300.0: my_exp = 1.942426395241234e+130 relative error 1.1e-14
Twelve terms on a range of already give errors at the level of floating-point rounding (about ). At the error grows to about because with is itself rounded before the subtraction; real libraries store as a high and a low part (Cody–Waite reduction) to keep exact. GPU shader functions and fixed-point game math use the same two steps with fewer terms, trading accuracy for speed.
In physics: the small-angle approximation
Keeping only the first term, ( in radians) and . The error of is about , so for small angles it is tiny. This turns the pendulum equation into a solvable one, giving the period , and lets game code use cheap approximations for small rotations per frame.
import math
print("angle sin θ θ (rad) relative error")
for deg in [1, 5, 10, 20, 45]:
th = math.radians(deg)
print(f"{deg:4d}° {math.sin(th):.6f} {th:.6f} {(th - math.sin(th)) / math.sin(th):.3%}")angle sin θ θ (rad) relative error
1° 0.017452 0.017453 0.005%
5° 0.087156 0.087266 0.127%
10° 0.173648 0.174533 0.510%
20° 0.342020 0.349066 2.060%
45° 0.707107 0.785398 11.072%
Up to about 10° the error stays below 1%, which is why the approximation is standard for pendulums and small steering angles.
Exercises
Exercise 1: A Maclaurin series by substitution
Write the first four non-zero terms of the Maclaurin series of .
Answer
Solution
Put into the series of :
Exercise 2: Taylor series away from zero
Find the Taylor polynomial of degree 3 for at .
Answer
Solution
Exercise 3: A limit with series
Use the sine series to find as .
Answer
Solution
Exercise 4: Your own sine
Write my_sin(x) that first reduces x into (using math.remainder(x, 2π)) and then sums the Taylor series up to . Compare it with math.sin at .
Answer
and agree to about . reduces to , near the edge of , and the error is about : the first omitted term is that size. More terms, or reducing further with symmetries, would fix it. Without range reduction, would be hopeless.
Solution
import math
def my_sin(x):
r = math.remainder(x, 2 * math.pi) # now -π ≤ r ≤ π
return sum((-1) ** k * r ** (2 * k + 1) / math.factorial(2 * k + 1) for k in range(8))
for x in [1, 10, 100]:
print(x, f"{my_sin(x):.12f}", f"{math.sin(x):.12f}", f"{abs(my_sin(x) - math.sin(x)):.1e}")1 0.841470984808 0.841470984808 2.8e-15
10 -0.544021085826 -0.544021110889 2.5e-08
100 -0.506365641110 -0.506365641110 3.3e-15
Test yourself
What is the coefficient of in the Maclaurin series of ?
Why do math libraries apply range reduction before using a polynomial?
- Polynomials only work for integers
- A short polynomial is accurate only near its centre, so the input is first moved into a small range
- To avoid computing derivatives
- Range reduction is exact for every function
The small-angle approximation has an error of roughly what size?
- It is exact