“If derivatives tell you the slope here, Taylor series tell you the whole function near here.”
For a function with enough derivatives at ,
Setting gives the Maclaurin series. Example:
A degree‑ truncation
approximates near with remainder .
Use‑case | Where Taylor pops up |
---|---|
Activation function kernels | Approximating exp , tanh , GELU on edge devices. |
Transformers | Rotary / ALiBi positional encodings derive from low‑order series of . |
Gradient checkpoints | Cheap polynomial surrogates during backward pass to save memory. |
# calc-05-taylor/taylor_error_exp.py
import numpy as np, math, matplotlib.pyplot as plt
from math import factorial
def maclaurin_exp(x, n):
"""Return T_n(x) for e^x."""
return sum((x**k)/factorial(k) for k in range(n+1))
xs = np.linspace(-3, 3, 400)
true = np.exp(xs)
plt.figure(figsize=(6,4))
for n in [1, 2, 4, 6, 8]:
approx = maclaurin_exp(xs, n)
err = np.abs(approx - true)
plt.plot(xs, err, label=f"n={n}")
plt.yscale("log")
plt.xlabel("x"); plt.ylabel("|e^x - T_n(x)| (log)")
plt.title("Absolute error of Maclaurin truncations of e^x")
plt.legend(); plt.tight_layout(); plt.show()
What to look for: each +2 degree roughly squares the accuracy radius around 0.
# calc-05-taylor/animate_exp.py
import numpy as np, matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from math import factorial
# domain & true curve
xs = np.linspace(-3, 3, 400)
true = np.exp(xs)
fig, ax = plt.subplots(figsize=(6,4))
line, = ax.plot([], [], lw=2)
ax.plot(xs, true, 'k--', label="e^x")
ax.set_xlim(-3, 3); ax.set_ylim(-1, 20)
ax.set_title("Building e^x via Maclaurin truncations")
ax.legend()
def taylor_poly(x, n):
return sum((x**k)/factorial(k) for k in range(n+1))
def init():
line.set_data([], [])
return line,
def update(frame):
y = taylor_poly(xs, frame)
line.set_data(xs, y)
line.set_label(f"T_{frame}(x)")
ax.legend()
return line,
anim = FuncAnimation(fig, update, frames=range(0, 11), init_func=init,
interval=800, blit=True)
anim.save("exp_taylor.gif", writer="pillow")
The saved GIF shows the polynomial growing degree‑by‑degree until it hugs on a wider interval.
exp
for logits > 7 avoids overflow.Push solutions to calc-05-taylor/
and tag v0.1
.
Next episode: Calculus 6 – Gradient, Jacobian, Hessian: Stepping into Multiple Dimensions.