Module contents
Lesson 4 of 20Review 90 min

Taylor in one variable: polynomials, remainders and power series

A review of Taylor's theorem with its three remainder forms (Peano, Lagrange and integral), and power series with their radius of convergence. Smooth and analytic functions are distinguished, and complex singularities are shown to determine the radius. The lab builds exp from scratch as a mathematical library does: argument reduction plus a polynomial with an error bound.

After this lesson you can

  • State and prove Taylor's theorem with Lagrange and integral remainders.
  • Bound the error of a Taylor approximation and choose the minimum degree for a given tolerance.
  • Calculate convergence radii using Cauchy–Hadamard and explain them through singularities in the complex plane.
  • Operate with complex numbers in polar form and derive Euler's formula from the exponential power series.
  • Distinguish C^∞ functions from analytic functions using the e^{-1/x²} counterexample.
  • Implement an elementary function with argument reduction, Horner evaluation and a guaranteed error bound.

Before you start

Motivation: every local model is a Taylor polynomial

Almost everything calculated in ML, optimization and numerical analysis relies on one idea: near a point, a complicated function resembles a polynomial. You have already used it without naming it.

  • Linearization is first-order Taylor. The derivative is the unique number with f(a+h)=f(a)+f′(a)h+o(h)f(a + h) = f(a) + f'(a)h + o(h). Each gradient descent step relies on that linear model, and its largest reasonable size is determined by what the model ignores: the second-order term.
  • Second-order optimization is second-order Taylor. Newton’s method minimizes f(a)+f′(a)h+12f′′(a)h2f(a) + f'(a)h + \tfrac12 f''(a)h^2 instead of ff, and its step, h=−f′(a)/f′′(a)h = -f'(a)/f''(a), is the vertex of that parabola (its minimum when f′′(a)>0f''(a) > 0). In several variables, f′′f'' becomes the Hessian.
  • Finite differences are truncated Taylor expansions. Approximating f′(x)f'(x) by (f(x+h)−f(x))/h(f(x + h) - f(x))/h incurs an error exactly equal to the first-order Taylor remainder divided by hh, and checking a hand-coded gradient with the Taylor test verifies that the error decreases like h2h^2.
  • Your library’s elementary functions are polynomials. np.exp, np.log1p or torch.tanh reduce the argument to a small interval and evaluate a polynomial (or quotient of polynomials) whose degree was chosen using an error bound. At the end of the lesson you will build exp this way, with at most one ulp of error at every point you test.
  • Itô’s lemma and the delta-gamma approximation in quantitative finance are second-order Taylor expansions; in Itô’s, moreover, a term discarded in ordinary calculus, ( ⁣dB)2(\dd B)^2, cannot be discarded (you will see this in Itô’s lemma).

This lesson is a specialist-level review. It answers three questions left open by the high-school version: how much error is made (remainders and their bounds), how far the approximation extends when the whole series is summed (the radius of convergence), and why that radius is sometimes much smaller than the real graph suggests (the answer is in the complex plane, which we will construct along the way).

Intuition: increasing the order does not always help

The Taylor polynomial of order nn of ff at aa is the polynomial that shares with ff its value and first nn derivatives at aa. For f(x)=exf(x) = e^x at a=0a = 0, every derivative is 1 and

Tn(x)=1+x+x22+x36+⋯+xnn!.T_n(x) = 1 + x + \frac{x^2}{2} + \frac{x^3}{6} + \cdots + \frac{x^n}{n!}.

The natural question is whether Tn(x)→f(x)T_n(x) \to f(x) as n→∞n \to \infty, and for which xx. The following figure starts with f(x)=1/(1+x2)f(x) = 1/(1 + x^2), a function with nothing unusual on the real line: positive, bounded and infinitely differentiable.

InteractiveIncreasing Taylor order
ff and its Taylor polynomial T8T_{8} centered at a=0.00a = 0.00
Error ∣f(x)−Tn(x)∣|f(x) - T_n(x)| on logarithmic scale
110⁻⁵10⁻¹⁰10⁻¹⁵
  • ff
  • T8T_{8}
  • convergence interval (a−R,a+R)(a - R, a + R)
  • error and test points
8
n = 8
0.00
f(x)=11+x2f(x) = \dfrac{1}{1 + x^2}
T8(x)=1−x2+x4−x6+⋯T_{8}(x) = 1 - x^{2} + x^{4} - x^{6} + \cdots
Convergence radius RR1.000
Error at x=0.60x = 0.60 (inside)0.0044
Error at x=1.30x = 1.30 (outside)5.125
Radius R=1.00R = 1.00: inside (a−R,a+R)(a - R, a + R) error falls as nn grows; outside it grows without bound even where ff is perfectly smooth.
Above, ff in gray and its Taylor polynomial TnT_n in blue, centered at the black point, which you can drag. Below, the error ∣f(x)−Tn(x)∣|f(x) - T_n(x)| on a logarithmic scale. Increase nn or press play. With 1/(1+x2)1/(1 + x^2) the error plummets inside the blue band and explodes outside it, at ∣x∣>1|x| > 1, although the function has nothing special at x=±1x = \pm 1. Move the center and see how the band changes. Then compare with exe^x and sin⁡x\sin x (error falls everywhere), with ln⁡(1+x)\ln(1 + x) (the boundary is at x=−1x = -1, the band is symmetric and does not work at x>1x > 1) and with e−1/x2e^{-1/x^2} centered at 0: the polynomial is the line y=0y = 0 for every nn.

Three different behaviors, all with infinitely differentiable functions:

  1. Convergence on the entire line (exe^x, sin⁡x\sin x). The farther from the center, the higher the order needed, but raising it always suffices.
  2. Convergence on a symmetric interval around the center (ln⁡(1+x)\ln(1 + x), 1/(1+x2)1/(1 + x^2)). Inside, the error decreases geometrically with nn; outside, it grows geometrically. The interval’s half-width, the radius, depends on the center in a way the real graph does not explain: for 1/(1+x2)1/(1 + x^2) at aa it is 1+a2\sqrt{1 + a^2}.
  3. Convergence to the wrong function (e−1/x2e^{-1/x^2} at 0). Every derivative at 0 is zero, so Tn≡0T_n \equiv 0 and the series converges everywhere, but to 0, not to ff.

The rest of the lesson names and proves each phenomenon: the Taylor remainder explains the first, power series the second, the difference between smooth and analytic functions the third, and the complex plane explains why the second radius has its value.

The Taylor polynomial

The factor 1/k!1/k! makes the derivatives agree: differentiating kk times (x−a)k(x - a)^k gives k!k!, and every different power vanishes at x=ax = a after differentiating it kk times (lower powers disappear and higher powers retain a factor (x−a)(x - a)). Thus Tn(k)(a)=f(k)(a)T_n^{(k)}(a) = f^{(k)}(a) for k=0,…,nk = 0, \dots, n, and TnT_n is the unique polynomial of degree ≤n\le n with that property, because a polynomial of degree ≤n\le n is determined by its derivatives at a point.

But the property that matters is that TnT_n is the best polynomial approximation to ff near aa, in the precise sense of Landau notation.

Proof

Existence, by induction on nn. For n=1n = 1 this is the definition of derivative: f(x)−f(a)−f′(a)(x−a)=o(x−a)f(x) - f(a) - f'(a)(x - a) = o(x - a). Suppose the result holds for n−1n - 1 and let ff be as in the statement. The remainder R=f−TnR = f - T_n is differentiable near aa and its derivative is R′=f′−Tn′=f′−Tn−1(f′)R' = f' - T_n' = f' - T_{n-1}(f'), because differentiating the Taylor polynomial of ff gives that of f′f' with one lower order. The function f′f' satisfies the assumptions with n−1n - 1, so R′(t)=o((t−a)n−1)R'(t) = o((t - a)^{n-1}): given ε>0\eps > 0 there is δ>0\delta > 0 with ∣R′(t)∣≤ε∣t−a∣n−1|R'(t)| \le \eps|t - a|^{n-1} if ∣t−a∣<δ|t - a| < \delta. Since R(a)=0R(a) = 0, the mean value theorem gives, for 0<∣x−a∣<δ0 < |x - a| < \delta, a ξ\xi between aa and xx with

∣R(x)∣=∣R(x)−R(a)∣=∣R′(ξ)∣ ∣x−a∣≤ε∣ξ−a∣n−1∣x−a∣≤ε∣x−a∣n.|R(x)| = |R(x) - R(a)| = |R'(\xi)|\,|x - a| \le \eps|\xi - a|^{n-1}|x - a| \le \eps|x - a|^n.

Uniqueness. If pp and TnT_n satisfy the property, q=Tn−pq = T_n - p is a polynomial of degree ≤n\le n with q(x)=o((x−a)n)q(x) = o((x - a)^n). If q≠0q \neq 0, write it as q(x)=∑k=jnck(x−a)kq(x) = \sum_{k=j}^{n} c_k(x - a)^k with cj≠0c_j \neq 0. Then q(x)/(x−a)j→cj≠0q(x)/(x - a)^j \to c_j \neq 0, whereas q(x)/(x−a)j=(x−a)n−j⋅q(x)/(x−a)n→0q(x)/(x - a)^j = (x - a)^{n - j}\cdot q(x)/(x - a)^n \to 0. Contradiction.

∎

Uniqueness is the most useful computational tool in this topic: any polynomial of degree ≤n\le n approximating ff with error o((x−a)n)o((x - a)^n) is the Taylor polynomial, however it was obtained. No differentiation is needed.

The remainder: Peano, Lagrange and integral

The Peano remainder says the error is small compared with (x−a)n(x - a)^n as x→ax \to a, but gives no number: it does not let us guarantee, for example, that T13T_{13} calculates exe^x with 16 correct digits at [−0.35,0.35][-0.35, 0.35]. For that we need explicit expressions for the Taylor remainder. Two are classical: the integral form, obtained by integration by parts and an exact identity, and Lagrange’s form, deduced from it (or directly, with weaker assumptions, from the mean value theorem).

For n=0n = 0 this is the fundamental theorem of calculus, f(x)=f(a)+∫axf′(t) ⁣dtf(x) = f(a) + \int_a^x f'(t)\dd t. To pass to n=1n = 1, integrate by parts with u=f′(t)u = f'(t) and  ⁣dv= ⁣dt\dd v = \dd t, but choose the antiderivative v=−(x−t)v = -(x - t) instead of tt, so that it vanishes at endpoint t=xt = x:

∫axf′(t) ⁣dt=[−f′(t)(x−t)]ax+∫axf′′(t)(x−t) ⁣dt=f′(a)(x−a)+∫axf′′(t)(x−t) ⁣dt.\int_a^x f'(t)\dd t = \Big[-f'(t)(x - t)\Big]_a^x + \int_a^x f''(t)(x - t)\dd t = f'(a)(x - a) + \int_a^x f''(t)(x - t)\dd t.

That is the whole trick: each integration by parts extracts one more polynomial term and raises the degree of the kernel (x−t)n(x - t)^n by one. The full induction is the first guided exercise in the lesson.

The integral remainder is exact, not a bound. The other forms follow from it. Since (x−t)n(x - t)^n does not change sign between aa and xx and f(n+1)f^{(n+1)} is continuous, the mean value theorem for integrals gives a ξ\xi between aa and xx with

Rn(x)=f(n+1)(ξ)n!∫ax(x−t)n ⁣dt=f(n+1)(ξ)(n+1)!(x−a)n+1.R_n(x) = \frac{f^{(n+1)}(\xi)}{n!}\int_a^x (x - t)^n\dd t = \frac{f^{(n+1)}(\xi)}{(n + 1)!}(x - a)^{n+1}.
Proof

Fix x≠ax \ne a and define, for tt between aa and xx, F(t)=f(x)−∑k=0nf(k)(t)(x−t)k/k!F(t) = f(x) - \sum_{k=0}^{n} f^{(k)}(t)(x - t)^k/k! and G(t)=(x−t)n+1G(t) = (x - t)^{n+1}. On differentiating FF, the sum telescopes:

 ⁣d ⁣dt[f(k)(t)(x−t)kk!]=f(k+1)(t)(x−t)kk!−f(k)(t)(x−t)k−1(k−1)!⟹F′(t)=−f(n+1)(t)(x−t)nn!.\frac{\dd}{\dd t}\left[\frac{f^{(k)}(t)(x - t)^k}{k!}\right] = \frac{f^{(k+1)}(t)(x - t)^k}{k!} - \frac{f^{(k)}(t)(x - t)^{k-1}}{(k - 1)!} \quad\Longrightarrow\quad F'(t) = -\frac{f^{(n+1)}(t)(x - t)^n}{n!}.

Also F(x)=G(x)=0F(x) = G(x) = 0, F(a)=Rn(x)F(a) = R_n(x) and G(a)=(x−a)n+1G(a) = (x - a)^{n+1}. Cauchy’s version of the mean value theorem gives ξ\xi between aa and xx with (F(x)−F(a))G′(ξ)=(G(x)−G(a))F′(ξ)(F(x) - F(a))G'(\xi) = (G(x) - G(a))F'(\xi), that is,

Rn(x) (n+1)(x−ξ)n=(x−a)n+1 f(n+1)(ξ)(x−ξ)nn!.R_n(x)\,(n + 1)(x - \xi)^n = (x - a)^{n+1}\,\frac{f^{(n+1)}(\xi)(x - \xi)^n}{n!}.

Since ξ≠x\xi \neq x, divide by (n+1)(x−ξ)n(n + 1)(x - \xi)^n to obtain the formula. This proof does not need f(n+1)f^{(n+1)} to be continuous or even integrable.

∎

The three forms answer different questions. Peano gives the order of magnitude as x→ax \to a and is used to calculate limits and expansions. Lagrange provides a computable bound if a derivative can be bounded, and determines the degree of a polynomial in a library. The integral is an exact identity and generalizes to several variables (as you will see in multivariable Taylor), operators and Itô’s formula.

The Lagrange bound has two drawbacks worth seeing before using it. First, f(n+1)f^{(n+1)} must be bounded over the entire interval, not at the center. Second, it is a sufficient condition: it may be much greater than the true error, or even fail to tend to zero when the error does.

InteractiveThe Lagrange error band
f(x)=exf(x) = e^x, T3T_{3} and band T3±T_{3} \pm bound
Actual error and bound on logarithmic scale
110⁻⁵10⁻¹⁰10⁻¹⁵2⁻⁵³
  • ff
  • T3T_{3}
  • Lagrange band and bound
  • actual error ∣Rn(x)∣|R_n(x)|
  • interval [−r,r][-r, r]
Function
3
2.20
Interval [−r,r][-r, r]
∣R3(x)∣≤M4 ∣x∣44!M4=max⁡[0,x]et=emax⁡(0,x)\begin{aligned} |R_{3}(x)| &\le \frac{M_{4}\,|x|^{4}}{4!} \\ M_{4} &= \max_{[0, x]} e^t = e^{\max(0, x)} \end{aligned}
Actual error ∣Rn(x)∣|R_n(x)|1.63
Lagrange bound8.809
Bound / actual error5.403
Theorem’s ξ\xi (between 0 and xx)0.513
Bound on [−r,r][-r, r] at degree 38.5 × 10⁻⁴
Minimum degree for 2−532^{-53} on [−r,r][-r, r]13
Actual error remains within the band, as guaranteed by the theorem.
Above, the Taylor polynomial at 0 (blue) surrounded by the orange band Tn±Mn+1∣x∣n+1/(n+1)!T_n \pm M_{n+1}|x|^{n+1}/(n + 1)!, within which the bound guarantees ff lies (gray). Below, on a logarithmic scale, the actual error (magenta) and the bound (dashed orange). Drag xx and change nn: actual error never exceeds the bound, and with exe^x the theorem's point ξ\xi appears on the axis. Then choose interval [−r,r][-r, r] and look at the minimum degree the bound requires for error 2−532^{-53}: with exe^x it rises from 13 at [−ln⁡2/2,ln⁡2/2][-\ln 2/2, \ln 2/2] to 33 at [−4,4][-4, 4]. Finally try ln⁡(1+x)\ln(1 + x) with x<−1/2x < -1/2: the series converges, but the bound grows with nn.

The minimum-degree reading summarizes the strategy behind every elementary-function implementation. To put the absolute error bound for exe^x below 2−532^{-53} (half the ulp of 1 in float64, of the order of rounding when exe^x is near 1), Lagrange requires degree 13 at [−ln⁡2/2,ln⁡2/2][-\ln 2/2, \ln 2/2], 18 at [−1,1][-1, 1], 24 at [−2,2][-2, 2] and 33 at [−4,4][-4, 4], and at [−700,700][-700, 700] it would be useless. But that is unnecessary: since ekln⁡2+r=2kere^{k\ln 2 + r} = 2^k e^r and multiplication by 2k2^k is exact in floating point, it suffices to calculate ere^r for ∣r∣≤ln⁡2/2|r| \le \ln 2/2. Reducing the interval is much cheaper than raising the degree, because the error depends on rn+1/(n+1)!r^{n+1}/(n + 1)!: dividing rr by 2 gains n+1n + 1 bits at once.

Power series and radius of convergence

If ff is C∞C^\infty we can sum all the terms and ask where the result converges. This leads to studying power series in their own right, without reference to any ff.

Proof

Apply the root test (from the series convergence lesson) to ∑∣ck(x−a)k∣\sum|c_k(x - a)^k|:

lim sup⁡k∣ck(x−a)k∣1/k=∣x−a∣ lim sup⁡k∣ck∣1/k=∣x−a∣R.\limsup_k |c_k(x - a)^k|^{1/k} = |x - a|\,\limsup_k |c_k|^{1/k} = \frac{|x - a|}{R}.

If it is less than 1, the series of absolute values converges. If it exceeds 1, infinitely many kk have ∣ck(x−a)k∣>1|c_k(x - a)^k| > 1, so the general term does not tend to zero and the series diverges.

∎

The convergence set is therefore an interval centered at aa, perhaps including one or both endpoints. When the limit exists, the ratio test gives the same result: R=lim⁡k∣ck/ck+1∣R = \lim_k |c_k/c_{k+1}|.

SeriesRRAt x−a=Rx - a = RAt x−a=−Rx - a = -R
∑xk\sum x^k1divergesdiverges
∑xk/k\sum x^k/k1diverges (harmonic)converges (Leibniz), to −ln⁡2-\ln 2
∑xk/k2\sum x^k/k^21convergesconverges
∑xk/k!\sum x^k/k!∞\infty
∑k! xk\sum k!\,x^k0

What makes power series so convenient is that, inside their interval, they can be treated as polynomials.

The radius staying unchanged is easy: lim sup⁡∣kck∣1/k=lim sup⁡∣ck∣1/k\limsup|k c_k|^{1/k} = \limsup|c_k|^{1/k} because k1/k→1k^{1/k} \to 1, and dividing by x−ax - a does not change convergence. The delicate part is that the derivative of the sum equals the sum of derivatives, an interchange of limits. It is justified by uniform convergence on every [a−ρ,a+ρ][a - \rho, a + \rho] with ρ<R\rho < R, and we will prove it in the lesson on interchanging limits. Applying the theorem kk times and evaluating at x=ax = a gives f(k)(a)=k! ckf^{(k)}(a) = k!\,c_k. Term-by-term integration also preserves the radius; for example, this gives arctan⁡x=∑k(−1)kx2k+1/(2k+1)\arctan x = \sum_k (-1)^k x^{2k+1}/(2k + 1) from 1/(1+x2)=∑k(−1)kx2k1/(1 + x^2) = \sum_k (-1)^k x^{2k}.

Analytic versus smooth functions

By the preceding theorem, an analytic function is C∞C^\infty and the series representing it near aa is necessarily its Taylor series at aa. The question is the converse: is every f∈C∞f \in C^\infty analytic? No, and the counterexample is the function in the first figure.

What fails is that the remainder does not tend to zero. This is the general criterion: Tn(x)→f(x)T_n(x) \to f(x) if and only if Rn(x)→0R_n(x) \to 0, and Lagrange gives a convenient sufficient condition. If ∣f(n)(t)∣≤CAnn!|f^{(n)}(t)| \le C A^n n! for every nn and every tt in II, then at every xx with ∣x−a∣<1/A|x - a| < 1/A (and the segment from aa to xx inside II)

∣Rn(x)∣≤CAn+1(n+1)! ∣x−a∣n+1(n+1)!=C (A∣x−a∣)n+1→0.|R_n(x)| \le \frac{C A^{n+1}(n + 1)!\,|x - a|^{n+1}}{(n + 1)!} = C\,\big(A|x - a|\big)^{n+1} \to 0.

For e−1/x2e^{-1/x^2} the derivatives near 0 grow faster than any CAnn!C A^n n!, and the bound breaks down.

Analytic functions are rigid: what they do on one piece determines what they do everywhere.

Proof

Let A={x∈I:f(k)(x)=0 para todo k}A = \{x \in I : f^{(k)}(x) = 0 \text{ para todo } k\}. It is nonempty (it contains the subinterval). It is closed in II because it is the intersection of the sets {f(k)=0}\{f^{(k)} = 0\}, closed because f(k)f^{(k)} are continuous. And it is open: if x0∈Ax_0 \in A, the Taylor series of ff at x0x_0 is zero and ff agrees with it near x0x_0, so ff vanishes in a neighborhood of x0x_0, as do all its derivatives. An interval cannot be split into two nonempty disjoint open sets, hence A=IA = I.

∎

The practical consequence is bump functions. The function ψ(x)=e−1/(1−x2)\psi(x) = e^{-1/(1 - x^2)} for ∣x∣<1|x| < 1 and ψ(x)=0\psi(x) = 0 elsewhere is C∞C^\infty (the argument is the same as for e−1/x2e^{-1/x^2}) and has compact support [−1,1][-1, 1]. By the identity principle it cannot be analytic: it vanishes on (1,2)(1, 2) without being identically zero. Such functions exist only because C∞C^\infty smoothness is much more flexible than analyticity, and they underlie mollifiers for regularizing functions and partitions of unity. The flexibility is extreme: a theorem of Borel guarantees that for any sequence (bk)(b_k) there is a f∈C∞f \in C^\infty with f(k)(0)=bkf^{(k)}(0) = b_k. With bk=(k!)2b_k = (k!)^2 the Taylor series is ∑k! xk\sum k!\,x^k, which has radius 0.

Complex numbers and Euler’s formula

To understand the second behavior in the first figure, the finite radius of 1/(1+x2)1/(1 + x^2), we must leave the real line. We need complex numbers, and while we are at it, we construct them with just what the rest of the course needs.

In polar form, multiplication becomes geometric. If zj=rj(cos⁡θj+isin⁡θj)z_j = r_j(\cos\theta_j + i\sin\theta_j), expanding the product and using the sum formulas for sine and cosine,

z1z2=r1r2(cos⁡(θ1+θ2)+isin⁡(θ1+θ2)).z_1z_2 = r_1r_2\big(\cos(\theta_1 + \theta_2) + i\sin(\theta_1 + \theta_2)\big).

Multiplying by zz scales by ∣z∣|z| and rotates by arg⁡z\arg z. Multiplying by ii rotates by 90°90°, which is why i2=−1i^2 = -1 rotates by 180°180°. This is the same geometry as the complex eigenvalues of a real matrix, which rotates and scales on an invariant plane.

InteractiveMultiplication rotates and scales
ReIm
  • zz and its angle
  • ww and its angle
  • zwzw: angles added
  • unit circle
View
zw=(1.3+0.75i)(0.5+1.2i)=−0.25+1.94i\begin{aligned} zw &= (1.3 + 0.75i)(0.5 + 1.2i) \\ &= -0.25 + 1.94i \end{aligned}
zz (modulus ∠ argument)1.50 ∠ 30.0°
ww1.30 ∠ 67.4°
zwzw1.95 ∠ 97.4°
∣z∣ ∣w∣|z|\,|w|1.95
arg⁡z+arg⁡w\arg z + \arg w97.4°
Triangles (0,1,z)(0, 1, z) and (0,w,zw)(0, w, zw) are similar: multiplying by ww rotates the first by arg⁡w\arg w and scales it by ∣w∣|w|.
Drag zz (orange) and ww (aqua). The product zwzw (magenta) has modulus ∣z∣∣w∣|z||w| and argument equal to the sum of the two angles, as the three concentric arcs show. The two shaded triangles, (0,1,z)(0, 1, z) and (0,w,zw)(0, w, zw), are similar: multiplying by ww rotates the first by angle arg⁡w\arg w and scales it by ∣w∣|w|. Move ww to ii and verify that zwzw is zz rotated by 90°90°. Then switch to ‘Powers’: the powers zkz^k form a spiral that closes if ∣z∣<1|z| < 1 and opens if ∣z∣>1|z| > 1, and partial sums of the geometric series ∑zk\sum z^k (blue) reach 1/(1−z)1/(1 - z) only inside the unit disk.

The modulus satisfies ∣z1z2∣=∣z1∣∣z2∣|z_1z_2| = |z_1||z_2| and ∣z1+z2∣≤∣z1∣+∣z2∣|z_1 + z_2| \le |z_1| + |z_2|, and C\C with distance ∣z−w∣|z - w| is R2\R^2 with the Euclidean distance, complete. Therefore everything seen about series carries over unchanged: an absolutely convergent complex series converges, and the root test and Cauchy–Hadamard theorem hold word for word. Only the geometry of the convergence set changes: {z:∣z−a∣<R}\{z : |z - a| < R\} is no longer an interval, but a disk. Hence the name “radius”.

The most important series is the exponential. Since ∣zk+1/(k+1)!∣ / ∣zk/k!∣=∣z∣/(k+1)→0|z^{k+1}/(k + 1)!|\,/\,|z^k/k!| = |z|/(k + 1) \to 0, the series

ez=∑k≥0zkk!e^z = \sum_{k \ge 0} \frac{z^k}{k!}

converges absolutely for every z∈Cz \in \C. Evaluated at a purely imaginary number z=iθz = i\theta, the powers of ii cycle through 1,i,−1,−i1, i, -1, -i, and the even terms are real and the odd ones imaginary:

eiθ=∑k≥0(iθ)kk!=(1−θ22!+θ44!−⋯)⏟k par+i(θ−θ33!+θ55!−⋯)⏟k impar=cos⁡θ+isin⁡θ.e^{i\theta} = \sum_{k\ge 0}\frac{(i\theta)^k}{k!} = \underbrace{\Big(1 - \frac{\theta^2}{2!} + \frac{\theta^4}{4!} - \cdots\Big)}_{k \text{ par}} + i\underbrace{\Big(\theta - \frac{\theta^3}{3!} + \frac{\theta^5}{5!} - \cdots\Big)}_{k \text{ impar}} = \cos\theta + i\sin\theta.

Separating the series into even and odd terms is valid because it converges absolutely (as absolute convergence justifies: the two subseries converge and sum to the total), and each parenthesis is the Taylor series of cos⁡\cos and sin⁡\sin, converging to those functions by Lagrange. This is Euler’s formula, eiθ=cos⁡θ+isin⁡θe^{i\theta} = \cos\theta + i\sin\theta, derived rather than defined.

InteractiveThe exponential series winds around the circle
eᶻReIm
  • terms with even kk
  • terms with odd kk
  • eze^z
  • unit circle
0
N = 0
3.14
zkk!=zk−1(k−1)!⋅zk\frac{z^k}{k!} = \frac{z^{k-1}}{(k-1)!}\cdot\frac{z}{k}
zz0.000 + 3.142i
Each step rotates by arg⁡z\arg z90.0°
and scales by ∣z∣/k|z|/k3.14/k
Partial sum S0S_{0}1.0000
Target eze^z−1.0000
∣S0−ez∣|S_{0} - e^z|2
Last term ∣z∣0/0!|z|^{0}/0!1
θ=π\theta = \pi: the spiral ends at −1-1. This is eiπ+1=0e^{i\pi} + 1 = 0.
Each arrow is a term zk/k!z^k/k!, placed after the previous one; the polygonal line traces partial sums SNS_N. Each term is the previous one multiplied by z/kz/k: it rotates by arg⁡z\arg z and scales by ∣z∣/k|z|/k. With z=iπz = i\pi, the initial state, the rotation is 90°90°, terms alternate between horizontal (orange, kk even, the cosine series) and vertical (aqua, kk odd, the sine series), and the spiral ends at −1-1. Drag zz along the imaginary axis and verify that the destination traces the unit circle. Disable the constraint to move zz in the plane: the destination becomes eRe⁡z(cos⁡Im⁡z+isin⁡Im⁡z)e^{\operatorname{Re} z}(\cos \operatorname{Im} z + i\sin\operatorname{Im} z). Press play with large ∣z∣|z|: the first terms grow before the factorial wins.

Two consequences close the circle. The first is ez+w=ezewe^{z + w} = e^z e^w for all z,w∈Cz, w \in \C, proved by multiplying the two series (the Cauchy product of two absolutely convergent series converges to the product) and grouping using the binomial theorem. With it, ex+iy=ex(cos⁡y+isin⁡y)e^{x + iy} = e^x(\cos y + i\sin y), polar form becomes z=reiθz = re^{i\theta} and the multiplication rule is simply r1eiθ1⋅r2eiθ2=r1r2ei(θ1+θ2)r_1e^{i\theta_1}\cdot r_2e^{i\theta_2} = r_1r_2e^{i(\theta_1 + \theta_2)}: the trigonometric sum formulas are property ez+w=ezewe^{z+w} = e^ze^w read in real and imaginary parts. The second is the identity eiπ=−1e^{i\pi} = -1, the figure’s initial state.

Why 1/(1+x2)1/(1 + x^2) has radius 1

Now we can explain the first figure. For real xx, 1/(x−i)=(x+i)/(x2+1)1/(x - i) = (x + i)/(x^2 + 1), so

11+x2=Im⁡1x−i.\frac{1}{1 + x^2} = \operatorname{Im}\frac{1}{x - i}.

Expand 1/(x−i)1/(x - i) around a real point aa with h=x−ah = x - a, as a geometric series:

1x−i=1(a−i)+h=1a−i⋅11+h/(a−i)=∑k≥0(−1)khk(a−i)k+1,∣h∣<∣a−i∣.\frac{1}{x - i} = \frac{1}{(a - i) + h} = \frac{1}{a - i}\cdot\frac{1}{1 + h/(a - i)} = \sum_{k \ge 0}(-1)^k\frac{h^k}{(a - i)^{k+1}}, \qquad |h| < |a - i|.

Taking the imaginary part, the Taylor coefficients of 1/(1+x2)1/(1 + x^2) at aa are ck=(−1)kIm⁡(a−i)−(k+1)c_k = (-1)^k\operatorname{Im}(a - i)^{-(k+1)}. In polar form, a−i=ρe−iβa - i = \rho e^{-i\beta} with ρ=1+a2\rho = \sqrt{1 + a^2} and β=arg⁡(a+i)∈(0,π)\beta = \arg(a + i) \in (0, \pi), so

ck=(−1)kρ−(k+1)sin⁡((k+1)β).c_k = (-1)^k\rho^{-(k+1)}\sin\big((k + 1)\beta\big).

Therefore ∣ck∣1/k≤ρ−(k+1)/k→1/ρ|c_k|^{1/k} \le \rho^{-(k+1)/k} \to 1/\rho, and equality is attained in the limit superior because sin⁡(mβ)\sin(m\beta) and sin⁡((m+1)β)\sin((m + 1)\beta) cannot both be small: from sin⁡((m+1)β)=sin⁡(mβ)cos⁡β+cos⁡(mβ)sin⁡β\sin((m + 1)\beta) = \sin(m\beta)\cos\beta + \cos(m\beta)\sin\beta, if ∣sin⁡(mβ)∣<12sin⁡β|\sin(m\beta)| < \tfrac{1}{2}\sin\beta, then ∣sin⁡((m+1)β)∣≥32sin⁡β−12sin⁡β>0|\sin((m + 1)\beta)| \ge \tfrac{\sqrt{3}}{2}\sin\beta - \tfrac{1}{2}\sin\beta > 0. The radius is exactly

R(a)=1+a2=∣a−i∣,R(a) = \sqrt{1 + a^2} = |a - i|,

the distance from aa to the points ±i\pm i, where 1/(1+z2)1/(1 + z^2) has its poles. On the real line there is no obstacle; the obstacle is at C\C, and the real convergence interval is the intersection with the real axis of a disk that cannot contain ±i\pm i.

The phenomenon is general, although its proof belongs to complex analysis and we only state it here: if ff is complex differentiable on the disk ∣z−a∣<ρ|z - a| < \rho, its Taylor series at aa converges to ff throughout that disk. Therefore the radius of convergence is the distance from the center to the nearest complex singularity (the nearest point at which ff can no longer be extended in this way). And it cannot be larger when ff blows up at that singularity: the sum of a power series is continuous, and thus bounded, on every closed disk contained in its convergence disk, so if it contained the singularity, the sum (which agrees with ff near aa and, by the identity principle in C\C, throughout the common region) would remain bounded near a point where ∣f∣→∞|f| \to \infty.

InteractiveThe disk of convergence lives in ℂ
Complex plane
RImRe
Real line: ff and T10T_{10}
  • convergence disk, its intersection with R\mathbb{R} and TnT_n
  • singularities
  • ff
  • test points a+0.75Ra + 0.75R and a+1.25Ra + 1.25R
Function
0.00
10
Distance to nearest singularity1.0000
Radius estimated from c0,…,c60c_0, \dots, c_{60} only1.0000
Error of T10T_{10} at a+0.75R=0.75a + 0.75R = 0.75 (inside)0.0203
Error of T10T_{10} at a+1.25R=1.25a + 1.25R = 1.25 (outside)5.679
f(x)=11+x2f(x) = \frac{1}{1 + x^2}: poles at ±i\pm i. Nothing special happens on the real line at a±Ra \pm R; the obstacle lies outside it.
On the left, the complex plane with the singularities of ff (red crosses) and the convergence disk of its Taylor series centered at real point aa, which you can drag along the axis. The thick segment is its intersection with the real line. On the right, ff and its Taylor polynomial on the real line. The main readout compares the distance to the nearest singularity with the radius estimated solely from coefficients c0,…,c60c_0, \dots, c_{60}, without knowing where the singularities are: they agree. With 1/(1+x2)1/(1 + x^2), move aa and see the disk grow like 1+a2\sqrt{1 + a^2}. With tanh⁡\tanh and the sigmoid, two functions used by neural networks, the radius at 0 is π/2\pi/2 and π\pi, although both are perfectly smooth and bounded on R\R. Increase the degree and compare the error at a point inside and another outside the disk.

With this rule we can read radii without calculating a single coefficient:

  • tanh⁡z=sinh⁡z/cosh⁡z\tanh z = \sinh z/\cosh z has poles where cosh⁡z=0\cosh z = 0, at z=iπ(k+12)z = i\pi(k + \tfrac12). At 0, radius π/2\pi/2.
  • The sigmoid σ(z)=1/(1+e−z)\sigma(z) = 1/(1 + e^{-z}) has poles where e−z=−1e^{-z} = -1, at z=iπ(2k+1)z = i\pi(2k + 1). At 0, radius π\pi; at aa, a2+π2\sqrt{a^2 + \pi^2}.
  • z/(ez−1)z/(e^z - 1), whose series defines the Bernoulli numbers, has a removable singularity at 0 and poles at 2πik2\pi ik, k≠0k \neq 0: radius 2π2\pi.
  • ln⁡(1+z)\ln(1 + z) has at z=−1z = -1, where 1+z=01 + z = 0, a branch point: there is no way to define it continuously in any neighborhood of −1-1. Radius 1+a1 + a at a>−1a > -1.

For people working with neural networks, the lesson is concrete: a Taylor polynomial of σ\sigma or tanh⁡\tanh at 0 does not work outside (−π,π)(-\pi, \pi) or (−π/2,π/2)(-\pi/2, \pi/2), however many terms are taken. If you need to approximate an activation by a polynomial on a wider interval, the Taylor expansion is the wrong tool and minimax approximation or Chebyshev approximation on that interval is the right one.

Applications

Finite-difference truncation error

Taylor’s theorem with Lagrange remainder gives the error of any finite-difference formula. For f∈C2f \in C^2, f(x+h)=f(x)+f′(x)h+12f′′(ξ)h2f(x + h) = f(x) + f'(x)h + \tfrac12 f''(\xi)h^2, so

f(x+h)−f(x)h=f′(x)+h2f′′(ξ).\frac{f(x + h) - f(x)}{h} = f'(x) + \frac{h}{2}f''(\xi).

The error is O(h)\bigO(h). For the central difference, with f∈C3f \in C^3, subtract the order-2 expansions of f(x+h)f(x + h) and f(x−h)f(x - h): the even terms cancel and f′(x)+h212(f′′′(ξ1)+f′′′(ξ2))f'(x) + \tfrac{h^2}{12}(f'''(\xi_1) + f'''(\xi_2)) remains. By the intermediate value theorem, the average of the two values of f′′′f''' is f′′′(ξ)f'''(\xi) for some ξ\xi, and

f(x+h)−f(x−h)2h=f′(x)+h26f′′′(ξ).\frac{f(x + h) - f(x - h)}{2h} = f'(x) + \frac{h^2}{6}f'''(\xi).

But truncation is not the only error. Each evaluation of ff has roundoff error of order ε∣f∣\eps|f|, with ε≈2.2×10−16\eps \approx 2.2\times 10^{-16}, and dividing by hh amplifies that error: the total forward-difference error is of order h2∣f′′∣+2ε∣f∣/h\tfrac{h}{2}|f''| + 2\eps|f|/h, minimized when h∼ε≈10−8h \sim \sqrt{\eps} \approx 10^{-8}. For the central difference, h∼ε1/3h \sim \eps^{1/3}.

[ ]Finite differences: truncation versus roundingBrowser
import numpy as np
import matplotlib.pyplot as plt

f, df = np.sin, np.cos
x0 = 1.0
eps = np.finfo(float).eps
hs = 10.0 ** -np.arange(1, 15.01, 0.25)

err_del = np.abs((f(x0 + hs) - f(x0)) / hs - df(x0))
err_cen = np.abs((f(x0 + hs) - f(x0 - hs)) / (2 * hs) - df(x0))

i, j = err_del.argmin(), err_cen.argmin()
print(f"hacia delante: mejor h = {hs[i]:.1e}, error {err_del[i]:.1e}   (sqrt(eps) = {np.sqrt(eps):.1e})")
print(f"centrada:      mejor h = {hs[j]:.1e}, error {err_cen[j]:.1e}   (eps^(1/3) = {np.cbrt(eps):.1e})")
print(f"con h = 1e-2:  error centrado {err_cen[np.argmin(np.abs(hs - 1e-2))]:.4e}, "
      f"Taylor predice h^2 |cos 1| / 6 = {1e-4 * np.cos(1) / 6:.4e}")

plt.loglog(hs, err_del, "o-", ms=3, label="hacia delante")
plt.loglog(hs, err_cen, "o-", ms=3, label="centrada")
plt.loglog(hs, hs / 2 * abs(np.sin(x0)), "--", color="gray", label="truncamiento h |f''| / 2")
plt.loglog(hs, hs**2 / 6 * abs(np.cos(x0)), ":", color="gray", label="truncamiento h² |f'''| / 6")
plt.loglog(hs, eps / hs, "-.", color="gray", label="redondeo ε / h")
plt.xlabel("h"); plt.ylabel("error en f'(1)"); plt.ylim(1e-14, 1); plt.legend(); plt.show()

The graph is V-shaped: truncation dominates on the right, with slope 1 or 2 depending on the formula, and roundoff on the left, with slope −1-1. The forward difference minimum is near h=10−8h = 10^{-8}, with about eight correct digits; the central one reaches twelve with h≈6×10−6h \approx 6\times 10^{-6}. And Taylor’s prediction for h=10−2h = 10^{-2} agrees with measured error to four digits. This is what the Taylor test does for gradients: if your gradient is correctly programmed, the error of f(x+hv)−f(x)−h∇f(x)⊤vf(x + h\vb{v}) - f(x) - h\grad f(x)\T\vb{v} falls like h2h^2; if it falls like hh, there is a bug.

The tanh approximation to GELU

The GELU activation is GELU⁡(x)=x Φ(x)\operatorname{GELU}(x) = x\,\Phi(x), with Φ\Phi the standard normal cumulative distribution function. Many implementations instead use

12x(1+tanh⁡(c (x+b x3))),c=2/π, b=0.044715,\tfrac12 x\big(1 + \tanh\big(c\,(x + b\,x^3)\big)\big), \qquad c = \sqrt{2/\pi},\ b = 0.044715,

proposed in the original paper (Hendrycks and Gimpel, 2016). Where do the constants come from? Taylor. On one hand, Φ(x)=12+12π(x−x36)+o(x4)\Phi(x) = \tfrac12 + \tfrac{1}{\sqrt{2\pi}}\big(x - \tfrac{x^3}{6}\big) + o(x^4), integrating the density’s series term by term. On the other, with u=c(x+bx3)u = c(x + bx^3) and tanh⁡u=u−u3/3+o(u4)\tanh u = u - u^3/3 + o(u^4),

12(1+tanh⁡u)=12+c2x+(cb2−c36)x3+o(x4).\tfrac12\big(1 + \tanh u\big) = \tfrac12 + \tfrac{c}{2}x + \Big(\tfrac{cb}{2} - \tfrac{c^3}{6}\Big)x^3 + o(x^4).

Equating the coefficient of xx gives c=2/2π=2/πc = 2/\sqrt{2\pi} = \sqrt{2/\pi}. Equating that of x3x^3, cb2−c36=−162π\tfrac{cb}{2} - \tfrac{c^3}{6} = -\tfrac{1}{6\sqrt{2\pi}}, gives b=23π−16≈0.04554b = \tfrac{2}{3\pi} - \tfrac16 \approx 0.04554. The constant used, 0.0447150.044715, is close but different: the cell checks that it reduces maximum error on the entire line, what matters in a network, while Taylor’s is optimal only near 0.

[ ]GELU: Taylor determines the constantsBrowser
import numpy as np
from scipy.special import erf

x = np.linspace(-6, 6, 120001)
gelu = 0.5 * x * (1 + erf(x / np.sqrt(2)))
c = np.sqrt(2 / np.pi)
b_taylor = 2 / (3 * np.pi) - 1 / 6
for nombre, b in [("Taylor", b_taylor), ("implementaciones", 0.044715)]:
    aprox = 0.5 * x * (1 + np.tanh(c * (x + b * x**3)))
    err = np.abs(aprox - gelu)
    cerca = np.abs(x) < 0.5
    print(f"b = {b:.6f} ({nombre:16s}): error máx en |x| < 0.5: {err[cerca].max():.1e}   en [-6, 6]: {err.max():.1e}")

Near 0 the Taylor constant wins because it matches one more term; over the entire line the fitted one wins. This tension recurs throughout the lesson: Taylor is the best local approximation, not the best on an interval.

Implementation from scratch: exp with guaranteed error

We will write exp(x) for every float64 as a math library does: argument reduction, a Taylor polynomial evaluated by Horner’s rule, and a degree chosen using the Lagrange bound. First, the two small pieces.

Horner. Evaluating c0+c1x+⋯+cnxnc_0 + c_1x + \cdots + c_nx^n by computing each power separately costs on the order of n2/2n^2/2 multiplications (or 2n2n if powers are reused) and accumulates errors in each power. Horner’s rule rewrites the polynomial as

c0+x(c1+x(c2+⋯+x(cn−1+x cn)⋯)),c_0 + x\Big(c_1 + x\big(c_2 + \cdots + x(c_{n-1} + x\,c_n)\cdots\big)\Big),

which is exactly nn multiplications and nn additions. Moreover, with coefficients decreasing like those of the exponential, roundoff errors in the inner stages are multiplied by small xx and barely matter.

The degree. For ∣r∣≤ln⁡2/2≈0.3466|r| \le \ln 2/2 \approx 0.3466 and f=exp⁡f = \exp, Lagrange gives ∣Rn(r)∣≤eln⁡2/2 rn+1/(n+1)!=2 rn+1/(n+1)!|R_n(r)| \le e^{\ln 2/2}\,r^{n+1}/(n + 1)! = \sqrt{2}\,r^{n+1}/(n + 1)!, and we seek the smallest nn with that bound below 2−532^{-53}.

[ ]Horner and the degree required by LagrangeBrowser
import math
import numpy as np

def lagrange_bound(M, r, n):
    """Cota de Lagrange del resto de orden n en [-r, r] si |f^(n+1)| <= M allí."""
    return M * r ** (n + 1) / math.factorial(n + 1)

def choose_degree(M, r, tol):
    n = 0
    while lagrange_bound(M, r, n) >= tol:
        n += 1
    return n

def horner(c, x):
    """c[0] + c[1] x + ... + c[n] x^n con n productos y n sumas."""
    y = np.zeros_like(x) + c[-1]
    for ck in c[-2::-1]:
        y = y * x + ck
    return y

R = math.log(2) / 2
for r in [R, 1.0, 2.0, 4.0, 8.0]:
    print(f"exp en [-{r:.4f}, {r:.4f}]: grado mínimo {choose_degree(math.exp(r), r, 2.0**-53)}")

N = choose_degree(math.sqrt(2), R, 2.0**-53)
C = np.array([1 / math.factorial(k) for k in range(N + 1)])
print(f"\ngrado elegido: {N}; cota {lagrange_bound(math.sqrt(2), R, N):.2e} < 2^-53 = {2.0**-53:.2e}")

rng = np.random.default_rng(0)
r = rng.uniform(-R, R, 1_000_000)
ref = np.exp(r)
por_potencias = sum(C[k] * r**k for k in range(N + 1))
por_horner = horner(C, r)
ulp = np.spacing(ref)
print(f"error máx término a término: {np.max(np.abs(por_potencias - ref) / ulp):.0f} ulp")
print(f"error máx con Horner:        {np.max(np.abs(por_horner - ref) / ulp):.0f} ulp")

Thirteen is the degree in the numerical exercise at the end. Note that the measured error with Horner is at most one ulp while term-by-term evaluation reaches several: the Lagrange bound controls truncation, but rounding depends on how evaluation is performed.

Argument reduction. Write x=kln⁡2+rx = k\ln 2 + r with k=round⁡(x/ln⁡2)k = \operatorname{round}(x/\ln 2) and ∣r∣≤ln⁡2/2|r| \le \ln 2/2. Then ex=2kere^x = 2^k e^r, and multiplication by 2k2^k only changes the float’s exponent (np.ldexp), without error. Care is needed only in computing rr: kln⁡2k\ln 2 is not representable and subtracting x−kln⁡2x - k\ln 2 would cancel digits. Cody and Waite’s trick splits ln⁡2\ln 2 into a high part with low bits zero, so k⋅altak\cdot\text{alta} is exact for the kk encountered, and a low part that corrects it.

[ ]exp from scratch, compared in ulps with np.expBrowser
import mpmath

LN2_HI = 6.93147180369123816490e-01   # ln 2 con los bits bajos de la mantisa a cero
LN2_LO = 1.90821492927058770002e-10   # ln 2 - LN2_HI
print("LN2_HI + LN2_LO == ln 2:", LN2_HI + LN2_LO == math.log(2), "  LN2_HI =", float.hex(LN2_HI))

def my_exp(x):
    x = np.asarray(x, dtype=float)
    k = np.rint(x / math.log(2))                       # x = k ln 2 + r, |r| <= ln2 / 2
    r = (x - k * LN2_HI) - k * LN2_LO                  # k * LN2_HI es exacto
    return np.ldexp(horner(C, r), k.astype(np.int64))  # e^x = 2^k e^r

def ulps(y, ref):
    return np.abs(y - ref) / np.spacing(np.abs(ref))

x = rng.uniform(-700, 700, 2_000_000)
u = ulps(my_exp(x), np.exp(x))
print(f"{x.size:,} puntos en [-700, 700]: error máx {u.max():.0f} ulp; idénticos a np.exp: {np.mean(u == 0):.1%}")

# ¿quién tiene razón cuando difieren? valor exacto con 200 bits, redondeado a float64
mpmath.mp.prec = 200
xs = x[:2000]
exacto = np.array([float(mpmath.exp(mpmath.mpf(float(v)))) for v in xs])
print(f"frente al valor correctamente redondeado: my_exp {ulps(my_exp(xs), exacto).max():.0f} ulp, "
      f"np.exp {ulps(np.exp(xs), exacto).max():.0f} ulp")

# sin reducción de argumento: grado 59 alrededor de 0
c60 = np.array([1 / math.factorial(k) for k in range(60)])
for v in [1.0, 10.0, 20.0, -20.0]:
    ingenua = float(horner(c60, np.array(v)))
    print(f"sin reducir, x = {v:6.1f}: error relativo {abs(ingenua - math.exp(v)) / math.exp(v):.1e}")

A few lines suffice to match np.exp within one ulp at two million points, and where they differ neither is always correctly rounded. Without reduction, however, the same method fails: at x=20x = 20 truncation is already noticeable with 60 terms, and at x=−20x = -20 the result is garbage, because the series sums terms of size 2020/20!≈4×10720^{20}/20! \approx 4\times 10^7 with alternating signs to obtain 2×10−92\times 10^{-9}, catastrophic cancellation. Reduction avoids both problems at once.

ln(1 + x) for small x

The same analysis explains why np.log1p exists. For ∣x∣≤ε/4|x| \le \eps/4, 1 + x rounds to 1 and np.log(1 + x) returns 0 instead of ≈x\approx x. For somewhat larger xx, 1+x1 + x is computed with relative error up to ε/2\eps/2, an absolute error of the same size in the logarithm, and since ln⁡(1+x)≈x\ln(1 + x) \approx x, the relative error is of order ε/∣x∣\eps/|x|: with x=10−12x = 10^{-12} twelve digits are lost. The solution is never to form 1+x1 + x when xx is small. For ∣x∣<10−4|x| < 10^{-4} fourth-order Taylor suffices. If x>0x > 0 the series alternates with decreasing terms and the error is bounded by the first omitted term, x5/5x^5/5; if x<0x < 0 all terms have the same sign and the tail is bounded by ∣x∣5/(5(1−∣x∣))|x|^5/(5(1 - |x|)). In both cases absolute error is below 2.1×10−212.1\times 10^{-21}, and relative error below 2.1×10−172.1\times 10^{-17}. For the rest, Kahan’s trick ln⁡(u)⋅x/(u−1)\ln(u)\cdot x/(u - 1) with u=fl⁡(1+x)u = \operatorname{fl}(1 + x) compensates rounding of 1+x1 + x (Goldberg, 1991, theorem 4).

[ ]log1p from scratchBrowser
def my_log1p(x):
    x = np.asarray(x, dtype=float)
    u = 1 + x
    d = u - 1                                     # lo que realmente se sumó a 1 (exacto si u >= 1/2)
    with np.errstate(divide="ignore", invalid="ignore"):
        kahan = np.where(d == 0, x, np.log(u) * (x / d))
    taylor = x - x**2 / 2 + x**3 / 3 - x**4 / 4   # error < |x|^5 / 5 si |x| < 1e-4
    return np.where(np.abs(x) < 1e-4, taylor, kahan)

print("      x      error rel. log(1 + x)   error rel. my_log1p")
for v in [1e-1, 1e-3, 1e-5, 1e-8, 1e-12, 1e-15, 1e-18]:
    ref = np.log1p(v)
    print(f"  {v:7.0e}   {abs(np.log(1 + v) - ref) / ref:18.1e}   {abs(my_log1p(v) - ref) / ref:18.1e}")

X = np.concatenate([10 ** rng.uniform(-18, 0, 500_000), -(10 ** rng.uniform(-18, np.log10(0.75), 500_000))])
print(f"\n1e6 puntos en (-0.75, 1): my_log1p a {ulps(my_log1p(X), np.log1p(X)).max():.0f} ulp de np.log1p como mucho")

With libraries

sympy.series computes exact expansions, from which the radius can be estimated from the coefficients and compared with the distance to singularities found by sympy.solveset. The root ∣ck∣−1/k|c_k|^{-1/k} converges slowly, because if ∣ck∣≈CR−k|c_k| \approx C R^{-k} the factor C1/kC^{1/k} takes time to approach 1; the ratio of two consecutive nonzero coefficients, (∣ck1∣/∣ck2∣)1/(k2−k1)(|c_{k_1}|/|c_{k_2}|)^{1/(k_2 - k_1)}, eliminates CC and converges much faster.

[ ]Symbolic series and radius of convergenceBrowser
import sympy as sp

x = sp.symbols("x")
print(sp.series(sp.tan(x), x, 0, 8))
print(sp.series(x / (sp.exp(x) - 1), x, 0, 8), "\n")

casos = {
    "1/(1 + x^2)": (1 / (1 + x**2), 1 + x**2, 1.0),
    "tanh x": (sp.tanh(x), sp.cosh(x), float(sp.pi / 2)),
    "x/(e^x - 1)": (x / (sp.exp(x) - 1), sp.exp(x) - 1, float(2 * sp.pi)),
}
N = 24
for nombre, (f, den, esperado) in casos.items():
    s = sp.series(f, x, 0, N).removeO()
    c = np.array([float(s.coeff(x, k)) for k in range(N)])
    k = np.flatnonzero(c)
    k = k[k > 0]
    raiz = abs(c[k[-1]]) ** (-1 / k[-1])
    k1, k2 = k[-2], k[-1]
    cociente = (abs(c[k1]) / abs(c[k2])) ** (1 / (k2 - k1))
    print(f"{nombre:12s} raíz: {raiz:.4f}   cociente: {cociente:.6f}   distancia a la singularidad: {esperado:.6f}")
    print(f"{'':12s} ceros del denominador: {sp.solveset(den, x, domain=sp.S.Complexes)}")

In all three cases the ratio gives the radius to five or six digits and agrees with the distance to the closest zero of the denominator. In x/(ex−1)x/(e^x - 1) the zero x=0x = 0 does not count: the quotient has limit 1 there and the singularity is removable, so the first actual singularity is at ±2πi\pm 2\pi i.

For evaluating and manipulating polynomials, numpy.polynomial provides Horner (polyval) and operations in several bases. The final cell compares the Taylor polynomial of exe^x at [−ln⁡2/2,ln⁡2/2][-\ln 2/2, \ln 2/2] with the Chebyshev interpolant of the same degree. Taylor’s is exact at the center and worsens toward the endpoints; Chebyshev’s distributes error across the interval and, at the same degree, is 60 to over 500 times more accurate at degrees 6 to 9 (it reaches machine precision at degree 10, one or two fewer than Taylor). That is why real libraries do not use pure Taylor but minimax polynomials (you will see this in Chebyshev series); Taylor gives the starting point, approximate degree and bound guaranteeing the result.

[ ]numpy.polynomial: Taylor versus ChebyshevBrowser
from numpy.polynomial import Polynomial, Chebyshev
import matplotlib.pyplot as plt

t = np.linspace(-R, R, 20001)
print(" grado    Taylor (error rel.)    Chebyshev (error rel.)")
for d in range(6, 12):
    tay = Polynomial([1 / math.factorial(k) for k in range(d + 1)])
    che = Chebyshev.interpolate(np.exp, d, domain=[-R, R])
    et = np.max(np.abs(tay(t) - np.exp(t)) / np.exp(t))
    ec = np.max(np.abs(che(t) - np.exp(t)) / np.exp(t))
    print(f"  {d:3d}     {et:16.1e}     {ec:18.1e}")

print("\nPolynomial evalúa con Horner:", np.allclose(Polynomial(C)(t), horner(C, t), rtol=0, atol=1e-15))
d = 7
plt.plot(t, (Polynomial([1 / math.factorial(k) for k in range(d + 1)])(t) - np.exp(t)) / np.exp(t), label=f"Taylor, grado {d}")
plt.plot(t, (Chebyshev.interpolate(np.exp, d, domain=[-R, R])(t) - np.exp(t)) / np.exp(t), label=f"Chebyshev, grado {d}")
plt.xlabel("r"); plt.ylabel("error relativo"); plt.legend(); plt.show()

Common mistakes

Exercises

NumericThe degree of a float64 exp
After argument reduction, we must calculate ere^r for ∣r∣≤ln⁡2/2|r| \le \ln 2/2. What is the smallest degree nn such that the Lagrange bound on the Taylor remainder of exe^x at 0, throughout [−ln⁡2/2,ln⁡2/2][-\ln 2/2, \ln 2/2], is less than 2−532^{-53}?
NumericA sharper bound for free
Approximate sin⁡(0.1)\sin(0.1) by 0.1−0.13/60.1 - 0.1^3/6. Use that this polynomial is both T3T_3 and T4T_4 of sin⁡\sin at 0 to give the best Lagrange error bound you can, with ∣sin⁡(k)∣≤1|\sin^{(k)}| \le 1.
NumericA radius that is not an integer
Calculate the radius of convergence of ∑k≥1k!kkxk\displaystyle\sum_{k\ge 1}\frac{k!}{k^k}x^k.
NumericThe radius from another center
What is the convergence radius of the Taylor series of 1/(1+x2)1/(1 + x^2) centered at a=2a = 2?
QuizThe arctangent radius
The function arctan⁡\arctan is analytic, bounded and has all derivatives bounded on R\R. What is the convergence radius of its Taylor series at 0?
QuizTaylor for an activation
You want to approximate the sigmoid σ(x)=1/(1+e−x)\sigma(x) = 1/(1 + e^{-x}) by its high-degree Taylor polynomial at 0 on the interval [−4,4][-4, 4]. What happens as you increase the degree?
QuizSmooth, analytic and their series
Which statements are true?

More than one answer may be correct.

NumericPredicting the error of a difference
Approximate the derivative of sin⁡\sin at x=1x = 1 with the central difference (sin⁡(1+h)−sin⁡(1−h))/(2h)(\sin(1 + h) - \sin(1 - h))/(2h) and h=0.01h = 0.01. According to the leading Taylor term, what is the absolute error?
ProofThe integral remainder, by parts
Prove: If f∈Cn+1f \in C^{n+1} on an interval containing aa and xx, then f(x)=∑k=0nf(k)(a)k!(x−a)k+1n!∫axf(n+1)(t)(x−t)n ⁣dtf(x) = \sum_{k=0}^{n} \frac{f^{(k)}(a)}{k!}(x - a)^k + \frac{1}{n!}\int_a^x f^{(n+1)}(t)(x - t)^n \dd t.
0
Proceed by induction on nn.

Step 1 of 4. How is the case n=0n = 0, f(x)=f(a)+∫axf′(t) ⁣dtf(x) = f(a) + \int_a^x f'(t)\dd t proved?

ProofAll derivatives of e^(−1/x²) vanish at 0
Prove: Let f(x)=e−1/x2f(x) = e^{-1/x^2} for x≠0x \neq 0 and f(0)=0f(0) = 0. Then ff is infinitely differentiable on R\R and f(n)(0)=0f^{(n)}(0) = 0 for every nn.
0
Away from 0 the function is a composition of C∞C^\infty functions; the entire problem is at the origin.

Step 1 of 4. What form do the derivatives of ff take for x≠0x \neq 0?

CodeHorner and the Lagrange degree
Implement taylor_eval(coeffs, x0, x) to evaluate ∑kck(x−x0)k\sum_k c_k (x - x_0)^k by Horner's rule (it must accept a number or NumPy array in x), and choose_degree(deriv_bound, r, tol) to return the smallest nn such that the Lagrange bound deriv_bound(n + 1) * r**(n + 1) / (n + 1)! is strictly less than tol. Here deriv_bound(m) bounds ∣f(m)∣|f^{(m)}| on the interval [x0−r,x0+r][x_0 - r, x_0 + r]. The tests use exp, sin and cos.
import math
import numpy as np

def taylor_eval(coeffs, x0, x):
  """Evalúa sum_k coeffs[k] * (x - x0)**k por Horner. x puede ser un número o un array."""
  # tu código
  return 0.0 * np.asarray(x, dtype=float)

def choose_degree(deriv_bound, r, tol):
  """Menor n con deriv_bound(n + 1) * r**(n + 1) / (n + 1)! < tol."""
  # tu código
  return 0
Shift+Enter to run

Summary

Key idea
The Taylor polynomial is the best local polynomial approximation; the remainder (Peano for order, Lagrange for a bound, the integral for an exact identity) says how far off it is; and the series converges only in a disk in the complex plane whose radius is the distance to the nearest singularity, however smooth the function is on the real line.
  • TnT_n is the unique polynomial of degree ≤n\le n with f−Tn=o((x−a)n)f - T_n = o((x - a)^n). By uniqueness, expansions are computed algebraically (substitution, product, quotient) without differentiating.
  • Integral remainder Rn=1n!∫axf(n+1)(t)(x−t)n ⁣dtR_n = \frac{1}{n!}\int_a^x f^{(n+1)}(t)(x - t)^n\dd t, by parts; from it, Lagrange Rn=f(n+1)(ξ)(x−a)n+1/(n+1)!R_n = f^{(n+1)}(\xi)(x - a)^{n+1}/(n + 1)!, whose bound requires bounding f(n+1)f^{(n+1)} throughout the interval.
  • A power series converges on ∣x−a∣<R|x - a| < R with 1/R=lim sup⁡∣ck∣1/k1/R = \limsup|c_k|^{1/k} (Cauchy–Hadamard), can be differentiated term by term with the same radius, and is the Taylor series of its sum.
  • Analytic implies C∞C^\infty, but not conversely: e−1/x2e^{-1/x^2} and bump functions are smooth and not analytic. Analytic functions obey the identity principle.
  • In C\C, multiplying by reiθre^{i\theta} scales by rr and rotates by θ\theta, and eiθ=cos⁡θ+isin⁡θe^{i\theta} = \cos\theta + i\sin\theta follows by separating the exponential series into even and odd terms.
  • 1/(1+x2)1/(1 + x^2) has radius 1+a2\sqrt{1 + a^2} at aa due to its poles at ±i\pm i; the sigmoid, π\pi at 0; tanh⁡\tanh, π/2\pi/2.
  • An elementary function is implemented by reducing the argument to a small interval (x=kln⁡2+rx = k\ln 2 + r) and evaluating by Horner a polynomial whose degree is fixed by the Lagrange bound: reducing the interval is much more effective than increasing the degree.