Taylor Polynomials¶
We approximate $f(x) = \ln(1 + x)$ by its Taylor polynomials at $c = 1$. The derivatives of $f$ are $$ f^{(k)}(x) = \frac{(-1)^{k-1} (k-1)!}{(1 + x)^k} \quad \text{for } k \geq 1, $$ so the Taylor polynomial of order $n$ is $$ p_n(x) = \ln(1 + c) + \sum_{k=1}^{n} \frac{(-1)^{k-1}}{k (1 + c)^k} (x - c)^k. $$
In [1]:
import numpy as np
import matplotlib.pyplot as plt
The function and its Taylor polynomials¶
In [2]:
def f(x):
return np.log(1 + x)
def taylor(x, n, c=1.0):
"""Taylor polynomial of order n for ln(1 + x), centered at c."""
p = np.log(1 + c) * np.ones_like(x)
for k in range(1, n + 1):
p += (-1) ** (k - 1) / (k * (1 + c) ** k) * (x - c) ** k
return p
Plots¶
Left: $f$ together with $p_n$ for several values of $n$. Right: the absolute errors $|f(x) - p_n(x)|$. All the errors vanish at $x = c$, and the error decreases as $n$ increases near $c$.
In [3]:
c = 1.0
x = np.linspace(0, 2, 201)
orders = [0, 1, 2, 3]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4.5))
for n in orders:
p = taylor(x, n, c)
ax1.plot(x, p, label=f"$p_{n}$")
ax2.plot(x, np.abs(f(x) - p), label=f"$|f - p_{n}|$")
ax1.plot(x, f(x), "k", linewidth=2, label="$f$")
ax1.set_xlabel("$x$")
ax1.set_title(r"$f(x) = \ln(1 + x)$ and Taylor polynomials")
ax1.legend()
ax2.set_ylim(0, 0.5)
ax2.set_xlabel("$x$")
ax2.set_title("Absolute error")
ax2.legend()
plt.show()