Module contents
Lesson 1 of 20Review 100 min

Limits, continuity and the derivative in one variable

A dense, rigorous review of single-variable differential calculus with an eye to what follows: ε–δ language, little-o and big-O notation, the derivative as the best linear approximation, the mean value theorem and Lipschitz continuity. Each result connects to a concrete ML use: activation Lipschitz constants, finite-difference error and guaranteed bisection.

After this lesson you can

  • Write and negate the ε–δ definitions of limits and continuity, and prove simple limits with them.
  • Use o(h) and O(h) notation to express approximations and error orders.
  • Characterize the derivative as the unique linear approximation with o(h) error and derive differentiation rules from it.
  • Apply the mean value theorem to bound differences and obtain Lipschitz constants from derivative bounds.
  • Implement bisection with a guaranteed iteration count and measure difference-quotient error as a function of h.

Before you start

Motivation: guarantees, counterexamples and constants

You already know how to differentiate. This lesson concerns what lies beneath: precise language for “approaches,” “is small,” and “does not change too much,” plus theorems turning those phrases into usable inequalities. In ML this language appears whenever someone asks for a guarantee rather than an impression.

  • Algorithmic guarantees. Bisection finds a continuous-function root with a preset error in ⌈log⁡2((b−a)/tol)⌉\lceil \log_2((b - a)/\mathrm{tol}) \rceil steps, no more. That count follows from a proof, not an experiment: the intermediate value theorem.
  • Counterexamples. Function sin⁡(1/x)\sin(1/x) equals 00 at all x=1/(nπ)x = 1/(n\pi) and 11 at all x=1/(π/2+2nπ)x = 1/(\pi/2 + 2n\pi). Regular sampling hitting the first points “proves” the limit at 0 is 0. Graphs and experiments deceive; quantified definitions do not.
  • Lipschitz constants. If ∣f(x)−f(y)∣≤L∣x−y∣\abs{f(x) - f(y)} \le L\abs{x - y}, perturbing input by δ\delta moves output by at most LδL\delta. This inequality underlies neural-network robustness certificates, GAN spectral normalization and, applied to gradients, L-smoothness fixing the admissible gradient-descent step. Activation constants (sigmoid 1/41/4, tanh 11) follow from one tool: the mean-value theorem.
  • Gradient checking. Before trusting hand-written backpropagation, compare it with a difference quotient (f(a+h)−f(a−h))/(2h)(f(a + h) - f(a - h))/(2h). Choosing hh requires understanding opposing errors: Taylor error favors small hh, while rounding penalizes it.

One idea unifies the lesson: the derivative is the best linear approximation to ff near a point, with error o(h)o(h). It yields differentiation rules, the chain rule (which grows into backpropagation in this module) and the mean-value theorem. Everything done here in one variable generalizes to the Fréchet derivative by replacing number f′(a)f'(a) with a matrix.

A limit as a game between adversaries

“f(x)f(x) tends to LL as xx tends to aa” has a misleading dynamic reading: nothing moves. It is a promise: however much output precision you demand, I can guarantee it by controlling the input. Cauchy and Bolzano stated it in words in the early 19th century; Weierstrass gave today’s ε\eps and δ\delta form.

Read it as a two-player game. The adversary chooses arbitrarily demanding tolerance ε>0\eps > 0. You respond with radius δ>0\delta > 0, possibly depending on ε\eps. You win if every domain xx within δ\delta of aa, excluding aa itself, satisfies ∣f(x)−L∣<ε\abs{f(x) - L} < \eps. The limit is LL if you have a winning strategy: an answer for every ε\eps.

Three details matter and appear in the figure:

  1. x=ax = a does not count (0<∣x−a∣0 < \abs{x - a}). A limit concerns behavior near aa, not at aa; ff need not be defined at aa and may have any value there.
  2. Quantifier order matters. ∀ε ∃δ\forall\eps\,\exists\delta lets δ\delta depend on ε\eps. Reversing order to ∃δ ∀ε\exists\delta\,\forall\eps asserts one δ\delta works for every tolerance, forcing ff to equal constant LL near aa (possibly except at aa).
  3. Any one δ\delta suffices, not the best. If δ\delta works, any δ′<δ\delta' < \delta also works.
InteractiveThe ε–δ game
f(x)=x2f(x) = x^2
witness
  • band ∣y−L∣<ε|y - L| < \varepsilon
  • band 0<∣x−a∣<δ0 < |x - a| < \delta
  • points outside the box
∀x: 0<∣x−1∣<0.300  ⇒  ∣f(x)−1.00∣<0.500×\forall x:\ 0 < |x - 1| < 0.300 \;\Rightarrow\; |f(x) - 1.00| < 0.500\quad \times
0.50
0.30
1.00
View
sup⁡∣f(x)−L∣\sup |f(x) - L| in the band0.690
Maximum δ\delta for this ε\varepsilon0.225
δmax⁡/ε\delta_{\max} / \varepsilon0.450
Rounds wonnone
You lose: x=1.30x = 1.30 lies in the vertical band and ∣f(x)−L∣=0.690≥ε|f(x) - L| = 0.690 \ge \varepsilon. Some δ\delta work: any below 0.2250.225.
The horizontal band is ∣y−L∣<ε\abs{y - L} < \varepsilon (adversary tolerance) and vertical band 0<∣x−a∣<δ0 < \abs{x - a} < \delta (your response). You win if the whole graph in the vertical band lies in the box; outside pieces are red and the red point is a witness. With x2x^2 always win: press ‘Next round’ several times and watch δmax⁡/ε\delta_{\max}/\varepsilon approach 1/21/2. Then try the jump and sin⁡(1/x)\sin(1/x): move LL anywhere and find ε\varepsilon for which no δ\delta exists. For Thomae’s function the natural candidate L=f(1/2)=1/2L = f(1/2) = 1/2 loses; which LL wins?

For f(x)=x2f(x) = x^2 at a=1a = 1, the largest δ\delta working for each ε\eps is δmax⁡=1+ε−1\delta_{\max} = \sqrt{1 + \eps} - 1 (the vertical band first hits the box above, where the parabola rises faster). For ε=0.5\eps = 0.5 it is 0.22470.2247, and as ε→0\eps \to 0, δmax⁡/ε→1/2\delta_{\max}/\eps \to 1/2. That 1/21/2 is 1/f′(1)1/f'(1): slope of ff determines the adversary’s allowable margin. This is not accidental and returns with derivatives.

Proving a limit

A limit proof writes the winning strategy: a formula for δ\delta as a function of ε\eps and verification it works. The task is always the same: bound ∣f(x)−L∣\abs{f(x) - L} by something depending only on ∣x−a∣\abs{x - a}.

When ff is less friendly, bound in two stages: first restrict δ≤1\delta \le 1 to control factors not tending to zero, then adjust the remainder. The first exercise does this for lim⁡x→2x2=4\lim_{x \to 2} x^2 = 4, choosing δ=min⁡(1,ε/5)\delta = \min(1, \eps/5).

Negating the definition: when no limit exists

To prove a limit is not LL, negate its definition. By quantifier laws, every ∀\forall becomes ∃\exists and vice versa, while implication P⇒QP \Rightarrow Q becomes P∧¬QP \wedge \neg Q:

lim⁡x→af(x)≠L  ⟺  ∃ε>0  ∀δ>0  ∃x∈D:0<∣x−a∣<δ ∧ ∣f(x)−L∣≥ε.\lim_{x \to a} f(x) \ne L \iff \exists \eps > 0\ \ \forall \delta > 0\ \ \exists x \in D:\quad 0 < \abs{x - a} < \delta \ \wedge\ \abs{f(x) - L} \ge \eps.

In the game, the adversary has one move, an ε\eps, against which every response loses. For each δ\delta a witness xx in the vertical band lies outside the box. The figure’s panel displays this when no δ\delta exists.

The example illustrates a general nonexistence pattern: two sequences tending to aa whose images tend to different values. The next theorem makes this exact and works in the other direction too.

Proof

(⇒\Rightarrow) Given ε\eps take the definition’s δ\delta. Since xn→ax_n \to a (sequence limits are reviewed in lesson 3), some NN satisfies ∣xn−a∣<δ\abs{x_n - a} < \delta for n≥Nn \ge N, and since xn≠ax_n \ne a, also 0<∣xn−a∣0 < \abs{x_n - a}. Thus ∣f(xn)−L∣<ε\abs{f(x_n) - L} < \eps for n≥Nn \ge N.

(⇐\Leftarrow) By contrapositive, suppose the limit is not LL. Negation gives ε>0\eps > 0 such that for each δ=1/n\delta = 1/n some xn∈Dx_n \in D satisfies 0<∣xn−a∣<1/n0 < \abs{x_n - a} < 1/n and ∣f(xn)−L∣≥ε\abs{f(x_n) - L} \ge \eps. This sequence tends to aa, excludes aa and f(xn)f(x_n) does not tend to LL.

∎

Notice “every.” Checking one sequence, ten, or regular samples proves nothing: f(1/(nπ))=0f(1/(n\pi)) = 0 for every nn yet sin⁡(1/x)\sin(1/x) has no limit. The reverse direction therefore uses definition negation, not experiments.

Uniqueness and limit algebra

Proof

By contradiction, suppose L≠ML \ne M and take ε=∣L−M∣/2>0\eps = \abs{L - M}/2 > 0. Each limit gives δ1\delta_1 and δ2\delta_2; with δ=min⁡(δ1,δ2)\delta = \min(\delta_1, \delta_2) and x∈Dx \in D satisfying 0<∣x−a∣<δ0 < \abs{x - a} < \delta (exists since aa is an accumulation point), ∣L−M∣≤∣L−f(x)∣+∣f(x)−M∣<2ε=∣L−M∣\abs{L - M} \le \abs{L - f(x)} + \abs{f(x) - M} < 2\eps = \abs{L - M}. Contradiction.

∎

This explains requiring aa to be an accumulation point: without points of DD near aa, the defining implication would hold vacuously for every LL.

Calculation rules are as expected: if f→Lf \to L and g→Mg \to M at aa, then f+g→L+Mf + g \to L + M, fg→LMfg \to LM and, if M≠0M \ne 0, f/g→L/Mf/g \to L/M. The sum uses triangle inequality with ε/2\eps/2 per term. Product adds and subtracts:

∣f(x)g(x)−LM∣≤∣f(x)∣ ∣g(x)−M∣+∣M∣ ∣f(x)−L∣,\abs{f(x)g(x) - LM} \le \abs{f(x)}\,\abs{g(x) - M} + \abs{M}\,\abs{f(x) - L},

together with boundedness of ff near aa (with ε=1\eps = 1, ∣f(x)∣<∣L∣+1\abs{f(x)} < \abs{L} + 1). Quotient also needs gg bounded away from 0, guaranteed by M≠0M \ne 0: near aa, ∣g(x)∣>∣M∣/2\abs{g(x)} > \abs{M}/2.

Continuity and the intermediate value theorem

If aa is an accumulation point of DD, this is equivalent to lim⁡x→af(x)=f(a)\lim_{x \to a} f(x) = f(a): the limit exists and equals the value. If aa is isolated in DD, ff is automatically continuous at aa (take δ\delta below the distance to other points). By sequential characterization, ff is continuous at aa iff xn→ax_n \to a implies f(xn)→f(a)f(x_n) \to f(a): continuous functions commute with limits, f(lim⁡xn)=lim⁡f(xn)f(\lim x_n) = \lim f(x_n).

Limit algebra yields continuity algebra: sums, products and quotients (where the denominator is nonzero) of continuous functions are continuous. Polynomials, exp⁡\exp, sin⁡\sin and cos⁡\cos are continuous on R\R, and log⁡\log on (0,∞)(0, \infty). Composition remains, with a two-line proof and a lesson.

Proof

Given ε\eps, continuity of ff at b=g(a)b = g(a) gives η>0\eta > 0 with ∣y−b∣<η⇒∣f(y)−f(b)∣<ε\abs{y - b} < \eta \Rightarrow \abs{f(y) - f(b)} < \eps. Continuity of gg at aa with tolerance η\eta gives δ\delta with ∣x−a∣<δ⇒∣g(x)−b∣<η\abs{x - a} < \delta \Rightarrow \abs{g(x) - b} < \eta. Chaining gives ∣x−a∣<δ⇒∣f(g(x))−f(b)∣<ε\abs{x - a} < \delta \Rightarrow \abs{f(g(x)) - f(b)} < \eps.

∎

The lesson: one layer’s tolerance is the ε\eps demanded of the previous one. The same chaining multiplies network Lipschitz constants layer by layer.

Bolzano and bisection

The intermediate value theorem looks obvious but is not: it fails in Q\Q. Function f(x)=x2−2f(x) = x^2 - 2 is continuous on [0,2]∩Q[0, 2] \cap \Q, changes sign and vanishes at no rational. The issue is holes in Q\Q; proof must use real completeness. We give an algorithmic proof.

Proof

It suffices to consider f(a)<0<f(b)f(a) < 0 < f(b) (for general yy apply to f−yf - y; for reversed signs use −f-f). Construct intervals [an,bn][a_n, b_n] with a0=aa_0 = a, b0=bb_0 = b: if m=(an+bn)/2m = (a_n + b_n)/2 satisfies f(m)<0f(m) < 0 take [an+1,bn+1]=[m,bn][a_{n+1}, b_{n+1}] = [m, b_n]; otherwise [an,m][a_n, m]. By construction f(an)<0≤f(bn)f(a_n) < 0 \le f(b_n) for every nn, sequence (an)(a_n) increases, (bn)(b_n) decreases, and bn−an=(b−a)/2nb_n - a_n = (b - a)/2^n.

A bounded monotone sequence converges (completeness), so an→ca_n \to c and bn→c′b_n \to c'; since bn−an→0b_n - a_n \to 0, c=c′c = c'. Continuity gives f(c)=lim⁡f(an)≤0f(c) = \lim f(a_n) \le 0 and f(c)=lim⁡f(bn)≥0f(c) = \lim f(b_n) \ge 0. Hence f(c)=0f(c) = 0.

∎

The proof is the bisection method and gives its guarantee. After nn steps root cc lies in [an,bn][a_n, b_n], length (b−a)/2n(b - a)/2^n, so any point in the interval is at most (b−a)/2n(b - a)/2^n from a root. To guarantee error ≤tol\le \mathrm{tol}, use

n=⌈log⁡2b−atol⌉n = \left\lceil \log_2 \frac{b - a}{\mathrm{tol}} \right\rceil

iterations plus initial evaluations at aa and bb. This worst-case bound is independent of ff: bisection always gains one bit per evaluation. Newton is far faster when ff is smooth but convergence has caveats (good starting point, f′f' away from zero); bisection requires only continuity and a sign change, so practical methods like Brent’s rely on it.

One-sided limits and monotone functions

In the jump example, the graph reached aa from two heights. Separating sides gives a finer object.

A limit exists iff both one-sided limits exist and agree. A discontinuity with both limits but f(a−)≠f(a+)f(a^-) \ne f(a^+) is a jump of size f(a+)−f(a−)f(a^+) - f(a^-). The figure’s jump has f(0−)=0f(0^-) = 0 and f(0+)=1f(0^+) = 1; sin⁡(1/x)\sin(1/x) has no one-sided limits at 0, a different discontinuity. Monotone functions can only have the first kind.

Proof

Set {f(x):α<x<c}\{f(x) : \alpha < x < c\} is bounded above by f(c)f(c), so has supremum s≤f(c)s \le f(c) (completeness again). Given ε\eps, supremum gives x0<cx_0 < c with f(x0)>s−εf(x_0) > s - \eps, and for x0<x<cx_0 < x < c monotonicity gives s−ε<f(x0)≤f(x)≤ss - \eps < f(x_0) \le f(x) \le s. With δ=c−x0\delta = c - x_0 obtain f(c−)=sf(c^-) = s. The right side is symmetric using infimum.

If ff is discontinuous at cc, then f(c−)<f(c+)f(c^-) < f(c^+) and open interval (f(c−),f(c+))(f(c^-), f(c^+)) is nonempty: choose rational qcq_c inside. For c<c′c < c' intervals do not overlap because f(c+)≤f(x)≤f(c′−)f(c^+) \le f(x) \le f(c'^-) for any xx between cc and c′c'. Thus c↦qcc \mapsto q_c injects discontinuities into countable Q\Q.

∎

The one-sided limits and monotone functions characterization has an immediate use: a monotone function can be discontinuous at every rational (sum jumps of size 2−n2^{-n} over an enumeration of Q\Q), but never behave like sin⁡(1/x)\sin(1/x).

Landau notation: little o and big O

When approximations are chained, writing ε\eps and δ\delta at each step is unbearable. Landau notation packages the limit definition into a symbol.

Thus o(1)o(1) means “something tending to 0,” o(h)o(h) means “something tending to 0 faster than hh,” and O(h2)\bigO(h^2) means “something bounded by a multiple of h2h^2.” Useful examples as h→0h \to 0:

sin⁡h=h+O(h3),eh=1+h+h22+o(h2),log⁡(1+h)=h+O(h2),11−h=1+h+O(h2).\sin h = h + \bigO(h^3), \qquad e^h = 1 + h + \tfrac{h^2}{2} + o(h^2), \qquad \log(1 + h) = h + \bigO(h^2), \qquad \frac{1}{1 - h} = 1 + h + \bigO(h^2).

And as n→∞n \to \infty: nlog⁡n=o(n2)n \log n = o(n^2), n100=o(2n)n^{100} = o(2^n), log⁡n=o(nα)\log n = o(n^\alpha) for every α>0\alpha > 0. The latter is algorithmic asymptotic notation; h→0h \to 0 describes approximation errors and governs this lesson.

Calculation rules for h→0h \to 0 and m,n≥0m, n \ge 0 follow directly from the definition:

  1. o(hn)+o(hn)=o(hn)o(h^n) + o(h^n) = o(h^n) and c⋅o(hn)=o(hn)c \cdot o(h^n) = o(h^n) for every constant cc. Likewise for O\bigO.
  2. hm⋅o(hn)=o(hm+n)h^m \cdot o(h^n) = o(h^{m+n}),  O(hm)⋅o(hn)=o(hm+n)\ \bigO(h^m) \cdot o(h^n) = o(h^{m+n}) and O(hm)⋅O(hn)=O(hm+n)\bigO(h^m)\cdot\bigO(h^n) = \bigO(h^{m+n}).
  3. o(hn)⊂O(hn)o(h^n) \subset \bigO(h^n) and O(hn+1)⊂o(hn)\bigO(h^{n+1}) \subset o(h^n): higher order is smaller.
  4. If φ(h)=O(h)\varphi(h) = \bigO(h) and ρ(k)→0\rho(k) \to 0 as k→0k \to 0 with ρ(0)=0\rho(0) = 0, then ρ(φ(h)) φ(h)=o(h)\rho(\varphi(h))\,\varphi(h) = o(h). This lemma makes the chain rule work.

The derivative as the best linear approximation

The quotient is the slope of the secant between aa and a+ha + h, and the definition says those slopes have a limit. Another reformulation generalizes to any dimension.

Proof

Define error r(h)=(f(a+h)−f(a)−mh)/hr(h) = \big(f(a + h) - f(a) - m h\big)/h for h≠0h \ne 0; the condition is exactly r(h)→0r(h) \to 0. Since r(h)=f(a+h)−f(a)h−mr(h) = \frac{f(a + h) - f(a)}{h} - m, the difference quotient tends to mm iff r(h)→0r(h) \to 0. This proves equivalence with m=f′(a)m = f'(a). For uniqueness, if m1m_1 and m2m_2 both satisfy it, subtraction gives (m1−m2)h=o(h)(m_1 - m_2)h = o(h), i.e. m1−m2=o(h)/h→0m_1 - m_2 = o(h)/h \to 0: constant m1−m2m_1 - m_2 is therefore zero.

∎

The geometry is literal. In a half-width-ww window centered at (a,f(a))(a, f(a)), vertical distance between graph and line f(a)+mhf(a) + m h at x=a+hx = a + h in window units is ∣h∣ ∣r(h)∣/w≤∣r(h)∣\abs{h}\,\abs{r(h)}/w \le \abs{r(h)}; at the edge ∣h∣=w\abs{h} = w it is exactly ∣r(h)∣\abs{r(h)}. Maximum visible deviation is thus order sup⁡0<∣h∣≤w∣r(h)∣\sup_{0 < \abs{h} \le w} \abs{r(h)}. Differentiability means zooming makes the graph indistinguishable from a line, and that line can only be tangent.

InteractiveZoom into the tangent line
f(x)=sin⁡x+x2/4,r(h)=f(a+h)−f(a)−m hhf(x) = \sin x + x^2/4,\qquad r(h) = \frac{f(a + h) - f(a) - m\,h}{h}
window: a ± 0.20
Relative error r(h)r(h) versus scale ∣h∣|h| (logarithmic)
  • ff
  • line f(a)+mhf(a) + m h
  • r(h)r(h), h>0h > 0
  • r(h)r(h), h<0h < 0
  • window scale
0.80
10 ×
1.10
f′(a)f'(a)1.0967
Half-width ww0.20
Deviation sup⁡0<∣h∣≤w∣r(h)∣\sup_{0<|h|\le w} |r(h)|0.026
Keep zooming: deviation in window widths is sup⁡∣r(h)∣\sup |r(h)| and tends to 0.
Top: half-width ww window about (a,f(a))(a, f(a)) with candidate slope mm; bottom: relative error r(h)r(h) versus ∣h∣\abs{h} on a log scale, from right (blue) and left (orange). Dashed line is window scale. Press ‘Continuous zoom’ with the smooth function and watch deviation fall below a pixel. Move mm: error tends to f′(a)−mf'(a) - m, not zero. Then try ∣x∣|x| at a=0a = 0 (the cusp never flattens), x2sin⁡(1/x)x^2\sin(1/x) (always oscillates yet flattens) and xsin⁡(1/x)x\sin(1/x) (does not flatten). What happens to ∣x∣|x| if aa moves away from 0?

Differentiation rules, one by one

Form f(a+h)=f(a)+f′(a)h+o(h)f(a + h) = f(a) + f'(a)h + o(h) turns derivative rules into Landau algebra. Write f=f(a)f = f(a), f′=f′(a)f' = f'(a) and likewise for gg.

Product. Multiply both expansions:

f(a+h) g(a+h)=(f+f′h+o(h))(g+g′h+o(h))=fg+(f′g+fg′) h+o(h),f(a + h)\,g(a + h) = \big(f + f'h + o(h)\big)\big(g + g'h + o(h)\big) = fg + (f'g + fg')\,h + o(h),

because all remaining products (f′g′h2f'g'h^2, f⋅o(h)f\cdot o(h), h⋅o(h)h\cdot o(h), o(h)2o(h)^2…) are o(h)o(h) by rules 1 and 2. By uniqueness, (fg)′=f′g+fg′(fg)' = f'g + fg'.

Reciprocal. If g(a)≠0g(a) \ne 0, with k=g′h+o(h)k = g'h + o(h),  1g+k=1g⋅11+k/g=1g(1−kg+O(k2))=1g−g′g2h+o(h)\ \frac{1}{g + k} = \frac{1}{g}\cdot\frac{1}{1 + k/g} = \frac{1}{g}\big(1 - \tfrac{k}{g} + \bigO(k^2)\big) = \frac{1}{g} - \frac{g'}{g^2}h + o(h), so (1/g)′=−g′/g2(1/g)' = -g'/g^2; quotient follows from product.

Chain rule. This is the lesson’s only subtlety.

The high-school proof multiplies and divides by g(a+h)−g(a)g(a + h) - g(a):

f(g(a+h))−f(g(a))h=f(g(a+h))−f(g(a))g(a+h)−g(a)⋅g(a+h)−g(a)h.\frac{f(g(a + h)) - f(g(a))}{h} = \frac{f(g(a + h)) - f(g(a))}{g(a + h) - g(a)} \cdot \frac{g(a + h) - g(a)}{h}.

It fails if g(a+h)=g(a)g(a + h) = g(a) for values of hh arbitrarily close to 0, and that happens: g(x)=x2sin⁡(1/x)g(x) = x^2\sin(1/x) vanishes at every x=1/(nπ)x = 1/(n\pi). The version with o(h)o(h) avoids the problem without ever dividing.

k(h)=g(a+h)−g(a)=g′(a) h+o(h)=O(h)\begin{aligned} k(h) &= g(a + h) - g(a) \\ &= g'(a)\,h + o(h) = \bigO(h) \end{aligned}
The increment of the inner layer is linear in h plus a small error; in particular it is O(h).
1/5

This is the proof that generalizes: in several variables, f′(b)f'(b) and g′(a)g'(a) will be Jacobian matrices and the rule will be their product, which is exactly what backpropagation computes. The derivative of a composition is the composition of the linear approximations.

Differentiability implies continuity; the converse is false

If ff is differentiable at aa, then f(a+h)−f(a)=f′(a)h+o(h)→0f(a + h) - f(a) = f'(a)h + o(h) \to 0: ff is continuous at aa. You will prove this step by step in the exercises. The converse fails in instructive ways:

  • ∣x∣\abs{x} and ReLU at 0. They are continuous, but the one-sided slopes differ: lim⁡h→0±∣h∣/h=±1\lim_{h \to 0^\pm} \abs{h}/h = \pm 1 for ∣x∣\abs{x}, and 11 and 00 for ReLU⁡\relu. In the figure, the peak looks the same at every scale, because ∣x∣\abs{x} is invariant under scaling. No mm makes r(h)→0r(h) \to 0 on both sides.
  • xsin⁡(1/x)x\sin(1/x) at 0 (with value 0 at 0). Continuous, and the difference quotient is sin⁡(1/h)\sin(1/h), which has no limit. Zooming in reproduces the fan of oscillations between the lines y=±xy = \pm x at every scale.
  • x2sin⁡(1/x)x^2\sin(1/x) at 0 (with value 0 at 0). Here the quotient is hsin⁡(1/h)→0h\sin(1/h) \to 0, so it is differentiable with f′(0)=0f'(0) = 0, although it oscillates infinitely often near 0. But for x≠0x \ne 0, f′(x)=2xsin⁡(1/x)−cos⁡(1/x)f'(x) = 2x\sin(1/x) - \cos(1/x), which has no limit at 0: the derivative exists everywhere and is not continuous. Functions with continuous derivatives form the class C1C^1, strictly smaller than the class of differentiable functions.
  • x3\sqrt[3]{x} at 0. The quotient is h−2/3→+∞h^{-2/3} \to +\infty: a vertical tangent, which is not an approximation of the form f(a)+mhf(a) + mh.

It can be much worse: in 1872 Weierstrass presented (published in 1875) a function continuous on all of R\R and differentiable nowhere, ∑nancos⁡(bnπx)\sum_n a^n\cos(b^n\pi x) with 0<a<10 < a < 1, bb an odd integer and ab>1+3π/2ab > 1 + 3\pi/2 (Hardy proved in 1916 that ab≥1ab \ge 1 suffices). And although a derivative need not be continuous, it cannot be arbitrary: Darboux’s theorem says every derivative has the intermediate value property. Therefore the sign function, which jumps from −1-1 to 11, is not the derivative of any function on R\R, whatever its value at 0.

Rolle, the mean value theorem and L’Hôpital

The theorems in this section move from local information (the derivative at each point) to global information (how ff changes on an interval). They all rest on Fermat’s lemma and the Weierstrass extreme value theorem, which you will prove in lesson 5: a continuous function on a closed bounded interval attains its maximum and minimum.

Proof

Suppose it is a local maximum. For small h>0h > 0, f(c+h)−f(c)≤0f(c + h) - f(c) \le 0, so the difference quotient is ≤0\le 0 and so is its right-hand limit, f′(c)f'(c). For h<0h < 0 the quotient is ≥0\ge 0 and the left-hand limit, which is the same f′(c)f'(c), is ≥0\ge 0. Hence f′(c)=0f'(c) = 0.

∎
Proof

By Weierstrass, ff attains on [a,b][a, b] a maximum MM and a minimum mm. If both are attained at the endpoints, M=m=f(a)M = m = f(a) and ff is constant: any cc works. Otherwise one is attained at an interior point cc, and by Fermat f′(c)=0f'(c) = 0.

∎

The mean value theorem says that some tangent is parallel to the secant: if a car travels 120 km in an hour, its speedometer read exactly 120 km/h at some instant. It follows from Rolle by tilting the graph until its endpoints are at the same height; you will do this in a guided exercise. First, look at it.

InteractiveMean value: parallel secants and tangents
f(x)=x3−3x,f(b)−f(a)b−a=1.000f(x) = x^3 - 3x,\qquad \frac{f(b) - f(a)}{b - a} = 1.000
c₁c₂
f′(x)f'(x) on (a,b)(a, b) and secant slope: each crossing is a cc
pendiente 1.000
  • ff
  • secant
  • parallel tangents and f′f'
aa, bb−2.00, 2.00
Secant slope1.0000
Points cc with matching f′(c)f'(c)−1.155, 1.155
2 points cc: the theorem guarantees at least one, not exactly one.
Drag the endpoints aa and bb along the graph. The secant is violet; in magenta, the tangent at each cc with f′(c)f'(c) equal to its slope. Below, f′f' on (a,b)(a, b) and the horizontal line at that slope: the cc are the intersections. For the cubic there are two; for the wave, several; for the parabola, always the midpoint. For ∣x∣|x| on [−1,2][-1, 2] there are none: which assumption fails, and what does f′f' do in the lower graph? With x\sqrt{x}, move aa to 00.

Three lessons from the figure. The theorem gives existence, not uniqueness: x3−3xx^3 - 3x on [−2,2][-2, 2] has a secant of slope 1 and f′(c)=3c2−3=1f'(c) = 3c^2 - 3 = 1 at c=±2/3≈±1.1547c = \pm 2/\sqrt3 \approx \pm 1.1547. In general cc cannot be calculated: it is a root of f′(x)=sf'(x) = s, which may be as hard as any equation, and the value of the theorem is that we need not know it. And the assumptions are precise: differentiability is required on the open interval, so x\sqrt{x} on [0,4][0, 4] satisfies the theorem (c=1c = 1) even though f′(0)f'(0) does not exist; but a single interior point without a derivative suffices to break it, as with ∣x∣\abs{x}, whose derivative jumps from −1-1 to 11 without taking the value 1/31/3.

The consequences are used every day:

  • If f′=0f' = 0 on an interval, ff is constant on it. (Apply the theorem between any two points.)
  • If f′≥0f' \ge 0 on an interval, ff is increasing; if f′>0f' > 0, strictly increasing.
  • If ∣f′∣≤L\abs{f'} \le L on an interval, then ∣f(x)−f(y)∣≤L∣x−y∣\abs{f(x) - f(y)} \le L\abs{x - y} on it. This opens the door to Lipschitz continuity.

Cauchy and L’Hôpital

Proof

The function φ(x)=(f(b)−f(a))g(x)−(g(b)−g(a))f(x)\varphi(x) = \big(f(b) - f(a)\big)g(x) - \big(g(b) - g(a)\big)f(x) is continuous on [a,b][a, b], differentiable on (a,b)(a, b) and satisfies φ(a)=f(b)g(a)−g(b)f(a)=φ(b)\varphi(a) = f(b)g(a) - g(b)f(a) = \varphi(b). Rolle gives a cc with φ′(c)=0\varphi'(c) = 0, which is the claim.

∎

Geometrically, the curve t↦(g(t),f(t))t \mapsto (g(t), f(t)) has a tangent parallel to the chord between its endpoints at some point. Taking g(x)=xg(x) = x recovers Lagrange. And Cauchy’s theorem yields L’Hôpital’s rule almost for free.

Proof

Redefine f(a)=g(a)=0f(a) = g(a) = 0, making them continuous at aa. For nearby x>ax > a, Cauchy’s theorem on [a,x][a, x] gives a cx∈(a,x)c_x \in (a, x) with f(x) g′(cx)=g(x) f′(cx)f(x)\,g'(c_x) = g(x)\,f'(c_x). Also g(x)≠0g(x) \ne 0: if g(x)=g(a)=0g(x) = g(a) = 0, Rolle would give a point between aa and xx with g′=0g' = 0. Thus f(x)/g(x)=f′(cx)/g′(cx)f(x)/g(x) = f'(c_x)/g'(c_x). When x→a+x \to a^+, also cx→a+c_x \to a^+, and the quotient tends to ℓ\ell. The left-hand case is the same.

∎

For example, applying it three times, lim⁡x→0x−sin⁡xx3=lim⁡1−cos⁡x3x2=lim⁡sin⁡x6x=16\lim_{x \to 0} \frac{x - \sin x}{x^3} = \lim \frac{1 - \cos x}{3x^2} = \lim \frac{\sin x}{6x} = \frac16, another way of saying sin⁡x=x−x3/6+o(x3)\sin x = x - x^3/6 + o(x^3). The rule gives a sufficient, not necessary, condition: x+sin⁡xx→1\frac{x + \sin x}{x} \to 1 as x→∞x \to \infty, while the quotient of derivatives, 1+cos⁡x1 + \cos x, has no limit. If f′/g′f'/g' does not converge, the rule says nothing. The Taylor expansion, which you will see in lesson 4, almost always does the same job with more information.

Lipschitz and Hölder continuity

Continuity says that for every ε\eps there is a δ\delta, but does not say which one, and that δ\delta may depend on the point. Many applications need an explicit, uniform relationship between the size of a perturbation and the size of its effect.

A Lipschitz function is continuous, uniformly so: δ=ε/L\delta = \eps/L works at every point at once (a special case of uniform continuity in lesson 5). Geometrically, fixing a point (x0,f(x0))(x_0, f(x_0)) on the graph, the condition says the graph never enters the vertical double cone ∣y−f(x0)∣>L∣x−x0∣\abs{y - f(x_0)} > L\abs{x - x_0}. The Lipschitz constant is the slope of the widest cone that can slide along the whole graph without touching it.

Proof

(≤\le) For x<yx < y in II, the mean value theorem gives a c∈(x,y)c \in (x, y) with ∣f(y)−f(x)∣=∣f′(c)∣ ∣y−x∣≤sup⁡∣f′∣ ∣y−x∣\abs{f(y) - f(x)} = \abs{f'(c)}\,\abs{y - x} \le \sup\abs{f'}\,\abs{y - x}. (≥\ge) For interior xx, ∣f′(x)∣=lim⁡y→x∣f(y)−f(x)∣/∣y−x∣\abs{f'(x)} = \lim_{y \to x} \abs{f(y) - f(x)}/\abs{y - x}, and each quotient is ≤Lip⁡(f)\le \operatorname{Lip}(f), so the limit is too.

∎
InteractiveThe Lipschitz cone
∣f′(x)∣|f'(x)| and level LL: red shows where ∣f′∣>L|f'| > L
L = 0.400
  • ff
  • forbidden cone ∣y−f(x0)∣>L∣x−x0∣|y - f(x_0)| > L|x - x_0|
  • ∣f′∣|f'|
0.400
-2.00
Minimum LL for this vertex0.204
Record while moving the vertex0.204
sup⁡∣f′∣\sup |f'| (theory)0.250
L≥sup⁡∣f′∣=1/4L \ge \sup|f'| = 1/4: no vertex can fail. This is a Lipschitz constant.
The red double cone, with its vertex at the point you drag, is the forbidden region ∣y−f(x0)∣>L∣x−x0∣\abs{y - f(x_0)} > L\abs{x - x_0}; portions of the graph entering it are marked red. Below are ∣f′∣|f'| and the level LL. With the sigmoid, lower LL until some vertex fails and press ‘Sweep vertex’: the record for the minimum LL per vertex stops at sup⁡∣f′∣=1/4\sup|f'| = 1/4, and every vertex placed where ∣f′∣>L|f'| > L fails. Repeat with tanh, softplus and GELU. With x\sqrt{x}, move the vertex to 0: is there any LL that works?

With the theorem, each activation’s constant follows in one line:

ActivationDerivativesup⁡∣f′∣\sup\abs{f'}Where
Sigmoid σ(x)=1/(1+e−x)\sigma(x) = 1/(1 + e^{-x})σ(1−σ)\sigma(1 - \sigma)1/41/4at x=0x = 0, where σ=1/2\sigma = 1/2
tanh⁡\tanh1−tanh⁡21 - \tanh^211at x=0x = 0
Softplus log⁡(1+ex)\log(1 + e^x)σ(x)\sigma(x)11not attained: σ<1\sigma < 1
ReLU⁡\relu00 or 11 (does not exist at 0)11directly: ∣max⁡(0,x)−max⁡(0,y)∣≤∣x−y∣\abs{\max(0, x) - \max(0, y)} \le \abs{x - y}
GELU x Φ(x)x\,\Phi(x)Φ(x)+x φ(x)\Phi(x) + x\,\varphi(x)Φ(2)+e−1/π≈1.129\Phi(\sqrt2) + e^{-1}/\sqrt\pi \approx 1.129at x=2x = \sqrt2

The sigmoid’s is the product p(1−p)p(1 - p) with p∈(0,1)p \in (0, 1), maximized at p=1/2p = 1/2. GELU’s follows by setting  ⁣d ⁣dx(Φ+xφ)=φ(x)(2−x2)\frac{\dd}{\dd x}\big(\Phi + x\varphi\big) = \varphi(x)(2 - x^2) to zero, and is an example of a popular activation (Hendrycks and Gimpel, 2016) with constant greater than 1. ReLU requires the direct definition because it is not differentiable at 0; the theorem does apply on an interval not containing 0.

For compositions, the rule is the chaining rule from before: ∣f(g(x))−f(g(y))∣≤Lip⁡(f) ∣g(x)−g(y)∣≤Lip⁡(f)Lip⁡(g) ∣x−y∣\abs{f(g(x)) - f(g(y))} \le \operatorname{Lip}(f)\,\abs{g(x) - g(y)} \le \operatorname{Lip}(f)\operatorname{Lip}(g)\,\abs{x - y}, so

Lip⁡(f∘g)≤Lip⁡(f) Lip⁡(g).\operatorname{Lip}(f \circ g) \le \operatorname{Lip}(f)\,\operatorname{Lip}(g).

Two consequences for networks. A chain of nn sigmoids has derivative bounded by 4−n4^{-n}: the simplest version of vanishing gradients and activation saturation. And the bound for an entire network is the product of the bounds of its layers, which spectral normalization (Miyato et al., 2018) exploits by forcing each linear layer to have constant 1. The product bound is not exact: σ∘σ\sigma \circ \sigma has constant 0.05900.0590, not 1/16=0.06251/16 = 0.0625, because the point where σ\sigma is steepest is not mapped to the point where the second layer is steepest. You will calculate this in an exercise.

Intermediate regularity: Hölder

x\sqrt{x} on [0,1][0, 1] is continuous (even uniformly) but not Lipschitz: with y=0y = 0, x/x=1/x→∞\sqrt{x}/x = 1/\sqrt{x} \to \infty. What it does satisfy is a weaker inequality.

With α=1\alpha = 1 it is Lipschitz; the smaller α\alpha is, the sharper the function may be at small scales, because ∣x−y∣α≫∣x−y∣\abs{x - y}^\alpha \gg \abs{x - y} when ∣x−y∣\abs{x - y} is small. The square root is 1/21/2-Hölder on [0,∞)[0, \infty) with C=1C = 1: for x≥y≥0x \ge y \ge 0, (y+x−y)2=x+2y(x−y)≥x(\sqrt{y} + \sqrt{x - y})^2 = x + 2\sqrt{y(x - y)} \ge x, hence x−y≤x−y\sqrt{x} - \sqrt{y} \le \sqrt{x - y}. Similarly xαx^\alpha is α\alpha-Hölder. On bounded intervals, if β<α\beta < \alpha, every α\alpha-Hölder function is β\beta-Hölder, giving a scale of regularity:

C1 en [a,b] ⇒ Lipschitz ⇒ α-Ho¨lder ⇒ uniformemente continua ⇒ continua.C^1 \text{ en } [a, b] \ \Rightarrow\ \text{Lipschitz} \ \Rightarrow\ \alpha\text{-Hölder} \ \Rightarrow\ \text{uniformemente continua} \ \Rightarrow\ \text{continua}.

The first implication uses that f′f' continuous on a compact set is bounded. No arrow reverses: ∣x∣\abs{x} is Lipschitz and not C1C^1, x\sqrt{x} is Hölder and not Lipschitz, and 1/log⁡(1/x)1/\log(1/x) on (0,1/2](0, 1/2] (extended by 0 at 0) is uniformly continuous without being Hölder of any order.

The most important example of Hölder regularity is not an elementary function: paths of Brownian motion are, with probability 1, α\alpha-Hölder on every bounded interval for every α<1/2\alpha < 1/2 and for no α≥1/2\alpha \ge 1/2; and, by a finer result of Paley, Wiener and Zygmund (1933), they are nowhere differentiable. That path irregularity is why stochastic calculus needs its own chain rule.

Implementation from scratch

First, bisection with the number of iterations guaranteed by the theorem. Two implementation details matter: the loop has a fixed number of steps (a while b - a > tol may not terminate if tol is smaller than the spacing between consecutive floats), and the sign is compared without multiplying f(a) * f(m), which can overflow or round to 0.

[ ]Bisection with a guaranteeBrowser
import math

def biseccion(f, a, b, tol):
    """Raíz de f en [a, b] con error <= tol garantizado. Devuelve (x, evaluaciones)."""
    fa, fb = f(a), f(b)
    evals = 2
    if fa == 0:
        return a, evals
    if fb == 0:
        return b, evals
    if (fa < 0) == (fb < 0):
        raise ValueError("f(a) y f(b) tienen el mismo signo: Bolzano no garantiza nada")
    n = max(0, math.ceil(math.log2((b - a) / tol)))   # iteraciones del teorema
    for _ in range(n):
        m = a + (b - a) / 2
        fm = f(m)
        evals += 1
        if fm == 0:
            return m, evals
        if (fm < 0) == (fa < 0):      # la raíz está en [m, b]
            a, fa = m, fm
        else:                         # la raíz está en [a, m]
            b = m
    return a + (b - a) / 2, evals     # a distancia <= (b - a)/2 <= tol/2 de la raíz

casos = [
    ("x³ − 2x − 5 en [2, 3]",   lambda x: x**3 - 2*x - 5,        2.0, 3.0, 2.0945514815423265),
    ("tanh(x) − x/2 en [1, 3]", lambda x: math.tanh(x) - x / 2,  1.0, 3.0, 1.9150080481544987),
    ("cos(x) − x en [0, 1]",    lambda x: math.cos(x) - x,       0.0, 1.0, 0.7390851332151607),
]
for nombre, f, a, b, raiz in casos:
    for tol in (1e-3, 1e-8, 1e-12):
        x, ev = biseccion(f, a, b, tol)
        n = math.ceil(math.log2((b - a) / tol))
        print(f"{nombre:24s} tol = {tol:.0e}:  x = {x:.15f}   |x − raíz| = {abs(x - raiz):.1e}"
              f"   evaluaciones = {ev} (cota: {n} + 2)")

# sin continuidad no hay garantía: 1/x cambia de signo en [-1, 2] y no tiene raíces
x, ev = biseccion(lambda x: 1 / x, -1.0, 2.0, 1e-10)
print(f"\n1/x en [-1, 2]: «raíz» x = {x:.2e}, pero f(x) = {1 / x:.2e}")

All three functions satisfy the bound in every case, with actual error below the tolerance (often well below: the bound is for the worst case). The root of x3−2x−5x^3 - 2x - 5 is the one Wallis used to illustrate Newton’s method in the seventeenth century. And with 1/x1/x bisection calmly returns a point 1.5×10−111.5\times 10^{-11} from the pole, where ∣f∣\abs{f} is almost 7×10107\times 10^{10}: without the continuity assumption, the theorem says nothing and neither does the algorithm.

Now the difference quotients. By Taylor’s theorem (which you will see in detail in lesson 4), if ff is sufficiently differentiable,

f(a+h)−f(a)h=f′(a)+f′′(a)2h+O(h2),f(a+h)−f(a−h)2h=f′(a)+f′′′(a)6h2+O(h4).\frac{f(a + h) - f(a)}{h} = f'(a) + \frac{f''(a)}{2}h + \bigO(h^2), \qquad \frac{f(a + h) - f(a - h)}{2h} = f'(a) + \frac{f'''(a)}{6}h^2 + \bigO(h^4).

In the central quotient the even terms cancel, and the truncation error goes from O(h)\bigO(h) to O(h2)\bigO(h^2). On a log-log scale, the error is a straight line of slope 1 or 2. But the computer does not calculate f(a+h)f(a + h), but its rounded value, with relative error up to u=2−53≈1.1×10−16u = 2^{-53} \approx 1.1\times 10^{-16} (unit roundoff, half the machine epsilon). Subtracting f(a+h)−f(a)f(a + h) - f(a) two nearly equal numbers preserves their absolute error, of order u∣f(a)∣u\abs{f(a)}, but not their magnitude: this is catastrophic cancellation. Divided by hh, the roundoff error is of order u∣f(a)∣/hu\abs{f(a)}/h and grows as hh decreases. Adding the two and minimizing, the optimal hh is of order u≈10−8\sqrt{u} \approx 10^{-8} for the forward quotient and u1/3≈10−5u^{1/3} \approx 10^{-5} for the central one.

[ ]Finite differences: error versus hBrowser
import numpy as np
import matplotlib.pyplot as plt

def adelante(f, a, h):
    return (f(a + h) - f(a)) / h

def centrado(f, a, h):
    return (f(a + h) - f(a - h)) / (2 * h)

a, exacta = 1.0, np.cos(1.0)                    # f = sin, f'(1) = cos(1)
h = 10.0 ** np.arange(-16, 0.01, 0.25)
err_d = np.abs(adelante(np.sin, a, h) - exacta)
err_c = np.abs(centrado(np.sin, a, h) - exacta)

# pendientes en la zona de truncamiento (h grande)
zd = (h >= 1e-5) & (h <= 1e-1)
zc = (h >= 1e-3) & (h <= 1e-1)
pd = np.polyfit(np.log10(h[zd]), np.log10(err_d[zd]), 1)[0]
pc = np.polyfit(np.log10(h[zc]), np.log10(err_c[zc]), 1)[0]
print(f"pendiente log-log: hacia delante {pd:.3f}, centrado {pc:.3f}")

i, j = np.argmin(err_d), np.argmin(err_c)
print(f"mejor h hacia delante: {h[i]:.1e}  (error {err_d[i]:.1e})")
print(f"mejor h centrado:      {h[j]:.1e}  (error {err_c[j]:.1e})")
u = 2.0 ** -53
print(f"modelo: h* = 2 sqrt(u|f|/|f''|) = {2 * np.sqrt(u):.1e},  "
      f"h* = (3u|f|/|f'''|)^(1/3) = {np.cbrt(3 * u * np.sin(1) / np.cos(1)):.1e}")
print(f"con h = 1e-12: error hacia delante {abs(adelante(np.sin, a, 1e-12) - exacta):.1e}")

plt.loglog(h, err_d, "o-", ms=3, label="hacia delante")
plt.loglog(h, err_c, "o-", ms=3, label="centrado")
plt.loglog(h, np.sin(1) / 2 * h, "--", color="gray", label="pendiente 1: |f''| h / 2")
plt.loglog(h, np.cos(1) / 6 * h**2, ":", color="gray", label="pendiente 2: |f'''| h² / 6")
plt.ylim(1e-17, 1)
plt.xlabel("h"); plt.ylabel("error absoluto"); plt.legend(); plt.show()

The measured slopes are 1 and 2, as Taylor predicts. The minima are where the model said: for the forward quotient, around h≈10−8h \approx 10^{-8} with error about 10−910^{-9} (half the float64 digits); for the central quotient, around h≈10−5h \approx 10^{-5} with error about 10−1310^{-13}. With h=10−12h = 10^{-12}, so small that it seems “more accurate”, the forward error is 4×10−54\times 10^{-5}: four orders of magnitude worse than with h=10−8h = 10^{-8}. Try this in the next figure, whose curves are calculated in your browser with the same arithmetic.

InteractiveThe error of difference quotients
Absolute error versus hh, both axes logarithmic
u·|f(a)|/h
  • forward f(a+h)−f(a)h\frac{f(a + h) - f(a)}{h}
  • centered f(a+h)−f(a−h)2h\frac{f(a + h) - f(a - h)}{2h}
  • models
f(a + h) =
f(a) =
1.0 × 10⁻⁴
Exact f′(a)f'(a)0.5403023059
Forward: value0.5402602314
Forward: error4.2 × 10⁻⁵
Centered: value0.5403023050
Centered: error9.0 × 10⁻¹⁰
Correct digits (forward / centered)4.1 / 8.8
Model h∗h^* (forward)2 × 10⁻⁸
Model h∗h^* (centered)8 × 10⁻⁶
Truncation region for both: forward-difference error falls as hh (slope 1), centered error as h2h^2 (slope 2), as Taylor predicts.
Absolute error versus hh, with both axes logarithmic, calculated live in float64. On the right truncation dominates (lines of slope 1 and 2); on the left, roundoff, which rises like u∣f(a)∣/hu|f(a)|/h with noise. Move hh to 10−1210^{-12} and look at the strip of digits: f(a+h)f(a + h) and f(a)f(a) share almost all their digits, which are crossed out in the subtraction. Switch to 1/x1/x at a=0.2a = 0.2: with more curvature the optimum moves left and the minimum error rises.

This is why torch.autograd.gradcheck uses central differences with h=10−6h = 10^{-6} by default and warns if inputs are not double precision: in float32, with u≈6×10−8u \approx 6\times 10^{-8}, the minimum central quotient error is around u2/3≈10−5u^{2/3} \approx 10^{-5} relative, too much to distinguish a correct gradient from a slightly wrong one. The full analysis, including the optimal choice of hh and the effect of rounding a+ha + h itself, is in finite differences.

Finally, a numerical estimate of Lipschitz constants. By the mean value theorem, each quotient (f(xi+1)−f(xi))/(xi+1−xi)\big(f(x_{i+1}) - f(x_i)\big)/(x_{i+1} - x_i) on a grid is f′(ξi)f'(\xi_i) for some ξi\xi_i, so their maximum is a lower bound on sup⁡∣f′∣\sup\abs{f'} that converges to it as the grid is refined, if f′f' is continuous.

[ ]Lipschitz constants on a gridBrowser
import numpy as np
from scipy.special import erf

def lip_malla(f, a, b, n):
    x = np.linspace(a, b, n + 1)
    return np.max(np.abs(np.diff(f(x)) / np.diff(x)))

sigma = lambda x: 1 / (1 + np.exp(-x))
activaciones = {
    "sigmoide": sigma,
    "tanh": np.tanh,
    "softplus": lambda x: np.logaddexp(0, x),
    "relu": lambda x: np.maximum(0, x),
    "gelu": lambda x: x * 0.5 * (1 + erf(x / np.sqrt(2))),
    "sigmoide∘sigmoide": lambda x: sigma(sigma(x)),
}
for nombre, f in activaciones.items():
    print(f"{nombre:18s} Lip ≈ {lip_malla(f, -10, 10, 200_000):.6f}")

print("\nraíz cuadrada en [0, 1]: el máximo crece sin cota al refinar")
for n in (10, 1_000, 100_000):
    print(f"  n = {n:>7d}:  max cociente = {lip_malla(np.sqrt, 0, 1, n):8.2f}   sqrt(n) = {np.sqrt(n):8.2f}")

The five activations give the constants in the table: 0.250.25, 11, almost 11 for softplus (at [−10,10][-10, 10] the maximum derivative is σ(10)≈0.99995\sigma(10) \approx 0.99995), 11 and 1.12891.1289. The composition of two sigmoids gives 0.058960.05896, below the bound 1/161/16. And for x\sqrt{x} the maximum is the first quotient, 1/n/(1/n)=n\sqrt{1/n}/(1/n) = \sqrt{n}, which grows without bound: there is no Lipschitz constant.

With libraries: SymPy as a check

SymPy computes exact limits and derivatives, and is useful for checking by hand what has been proved. Its answers confirm the examples in the lesson, including the pathological ones: the limit of sin⁡(1/x)\sin(1/x) at 0 comes out as AccumBounds(-1, 1), SymPy’s way of saying that values accumulate throughout [−1,1][-1, 1] and there is no limit.

[ ]Limits and derivatives with SymPyBrowser
import sympy as sp

x = sp.symbols("x", real=True)
print("lim sin(1/x)          =", sp.limit(sp.sin(1 / x), x, 0))
print("lim x sin(1/x)        =", sp.limit(x * sp.sin(1 / x), x, 0))
print("lim (x - sin x)/x³    =", sp.limit((x - sp.sin(x)) / x**3, x, 0))
print("|x|/x por la derecha  =", sp.limit(sp.Abs(x) / x, x, 0, "+"), "  por la izquierda =", sp.limit(sp.Abs(x) / x, x, 0, "-"))

f = x**2 * sp.sin(1 / x)
fp = sp.diff(f, x)
print("\nf = x² sin(1/x):  f'(x) =", fp)
print("  f'(0) por la definición, lim f(h)/h =", sp.limit(f / x, x, 0))
print("  lim f'(x) en 0 =", sp.limit(fp, x, 0), " (f' no es continua en 0)")
[ ]Exact Lipschitz constantsBrowser
import sympy as sp

x = sp.symbols("x", real=True)
casos = {
    "sigmoide": 1 / (1 + sp.exp(-x)),
    "tanh": sp.tanh(x),
    "gelu": x * (1 + sp.erf(x / sp.sqrt(2))) / 2,
}
for nombre, f in casos.items():
    d = sp.diff(f, x)
    criticos = sp.solve(sp.diff(d, x), x)           # extremos de f'
    valores = [sp.simplify(d.subs(x, c)) for c in criticos]
    mejor = max(valores, key=lambda v: abs(float(v)))
    print(f"{nombre:9s} f' crítica en {criticos}:  sup|f'| = {mejor} ≈ {float(mejor):.6f}")

# contraste con la estimación en malla del laboratorio anterior
print("\ndiferencia con la malla (gelu):", abs(float(mejor) - lip_malla(activaciones["gelu"], -10, 10, 200_000)))

solve finds the unique critical point of σ′\sigma' and tanh⁡′\tanh', at x=0x = 0, with exact values 1/41/4 and 11; for GELU, the points ±2\pm\sqrt2 and value 12+12erf⁡(1)+e−1/π\tfrac12 + \tfrac12\operatorname{erf}(1) + e^{-1}/\sqrt\pi, which agrees with the grid estimate to all the digits it can give. Note that maximizing ∣f′∣\abs{f'} also requires checking interval endpoints and behavior at infinity; here f′f' tends to constants (00 or 11) that do not exceed the interior maximum, except for softplus, where the supremum 11 is only attained in the limit and solve finds no critical point.

For roots, scipy.optimize provides bisection (bisect) and Brent’s method (brentq), which combines bisection, secant and inverse quadratic interpolation without losing the sign-change guarantee:

[ ]Our bisection versus SciPyBrowser
from scipy import optimize

f = lambda x: x**3 - 2 * x - 5
x_prop, ev = biseccion(f, 2.0, 3.0, 1e-12)
r_bis = optimize.bisect(f, 2.0, 3.0, xtol=1e-12, full_output=True)[1]
r_bre = optimize.brentq(f, 2.0, 3.0, xtol=1e-12, full_output=True)[1]
print(f"propia: {ev} evaluaciones    scipy.bisect: {r_bis.function_calls}    brentq: {r_bre.function_calls}")
print(f"raíces: {x_prop:.15f}  {r_bis.root:.15f}  {r_bre.root:.15f}")

SciPy’s bisection makes the same evaluations as ours, because there is no other way to meet the worst-case guarantee. Brent needs only a few: it exploits the smoothness of ff when available and returns to bisection when it is not. In practice it is the method used; bisection guarantees that the method cannot fail.

Common mistakes

Exercises

ProofA limit with ε and δ
Prove: lim⁡x→2x2=4\lim_{x \to 2} x^2 = 4.
0
Let ε>0\varepsilon > 0. Find δ>0\delta > 0 such that 0<∣x−2∣<δ0 < |x - 2| < \delta implies ∣x2−4∣<ε|x^2 - 4| < \varepsilon.

Step 1 of 3. How do you start bounding ∣x2−4∣\abs{x^2 - 4}?

NumericThe largest δ
For f(x)=x2f(x) = x^2 at a=1a = 1 with L=1L = 1 and ε=0.5\varepsilon = 0.5, what is the largest δ\delta such that 0<∣x−1∣<δ0 < |x - 1| < \delta implies ∣x2−1∣<0.5|x^2 - 1| < 0.5?
QuizNegating the definition
Which formula expresses that lim⁡x→af(x)≠L\lim_{x \to a} f(x) \ne L?
ProofDifferentiability implies continuity
Prove: If ff is differentiable at aa, then ff is continuous at aa. The converse is false.
0
Let ff be differentiable at aa, with derivative f′(a)f'(a).

Step 1 of 3. What exactly must be proved?

NumericThe sigmoid constant
Calculate the optimal Lipschitz constant on R\mathbb{R} of the sigmoid σ(x)=1/(1+e−x)\sigma(x) = 1/(1 + e^{-x}).
QuizWhich are Lipschitz on [0, 1]?
Which of these functions are Lipschitz on [0,1][0, 1]? For xsin⁡(1/x)x\sin(1/x), take the value 0 at x=0x = 0.

More than one answer may be correct.

NumericThe product bound is not exact
Calculate Lip(σ∘σ)=sup⁡x∣σ′(σ(x)) σ′(x)∣\mathrm{Lip}(\sigma \circ \sigma) = \sup_x |\sigma'(\sigma(x))\,\sigma'(x)| to four significant figures. The product bound gives 1/4⋅1/4=0.06251/4 \cdot 1/4 = 0.0625.
NumericHow many bisections?
A continuous function changes sign on [1,2][1, 2]. How many bisection iterations (excluding the two initial evaluations) guarantee finding a root with error at most 10−610^{-6}?
NumericA 0/0 limit
Calculate lim⁡x→0tan⁡x−xx3\lim_{x \to 0} \dfrac{\tan x - x}{x^3}.
QuizLandau rules
As h→0h \to 0, which statements are true?

More than one answer may be correct.

QuizThe best h
You approximate f′(1)f'(1) with f=sin⁡f = \sin in float64 using the central quotient (f(1+h)−f(1−h))/(2h)(f(1 + h) - f(1 - h))/(2h). Which of these hh gives the smallest error?
ProofThe mean value theorem from Rolle
Prove: If ff is continuous on [a,b][a, b] and differentiable on (a,b)(a, b), there exists c∈(a,b)c \in (a, b) with f′(c)=f(b)−f(a)b−af'(c) = \dfrac{f(b) - f(a)}{b - a}.
0
Call s=f(b)−f(a)b−as = \dfrac{f(b) - f(a)}{b - a} the slope of the secant. You may use Rolle's theorem.

Step 1 of 3. To which function do you apply Rolle?

CodeBisection with a guarantee
Implement bisect(f, a, b, tol) returning (x, n_evals): an x at distance at most tol from a root of f in [a, b] and the number of evaluations of f made. It must raise ValueError if f(a) and f(b) have the same sign (both strictly positive or both strictly negative), return the endpoint if f(a) == 0 or f(b) == 0, and perform no more than ceil(log2((b - a)/tol)) + 2 evaluations.
import math

def bisect(f, a, b, tol):
  """Devuelve (x, n_evals) con |x - raíz| <= tol."""
  # tu código: comprobar el cambio de signo, calcular el número de iteraciones
  # que garantiza el teorema y partir el intervalo por la mitad
  return (a + b) / 2, 0
Shift+Enter to run

Summary

Key idea
A limit is a winning strategy against any tolerance, and the derivative is the unique slope mm with f(a+h)=f(a)+mh+o(h)f(a + h) = f(a) + m h + o(h): in that form the differentiation rules are Landau algebra and the mean value theorem turns bounds on f′f' into global guarantees, such as Lipschitz constants.
  • lim⁡x→af(x)=L\lim_{x \to a} f(x) = L means ∀ε ∃δ ∀x (0<∣x−a∣<δ⇒∣f(x)−L∣<ε)\forall\eps\,\exists\delta\,\forall x\,(0 < \abs{x - a} < \delta \Rightarrow \abs{f(x) - L} < \eps). Negate it by changing each quantifier and exhibiting a witness for each δ\delta; it is equivalent to f(xn)→Lf(x_n) \to L for every sequence xn→ax_n \to a with xn≠ax_n \ne a.
  • Continuous functions commute with limits and compose. Bolzano’s theorem needs completeness of R\R and its proof is bisection, with ⌈log⁡2((b−a)/tol)⌉\lceil\log_2((b - a)/\mathrm{tol})\rceil guaranteed iterations.
  • Monotone functions have one-sided limits at every point; their discontinuities are jumps and form an at most countable set.
  • o(h)o(h) and O(h)\bigO(h) package ε\eps and δ\delta; the Landau equals sign denotes membership.
  • Differentiability implies continuity, not conversely (∣x∣\abs{x}, ReLU, xsin⁡(1/x)x\sin(1/x)); moreover a derivative can exist everywhere without being continuous (x2sin⁡(1/x)x^2\sin(1/x)). The chain rule is proved without dividing by g(a+h)−g(a)g(a + h) - g(a).
  • Rolle, Lagrange and Cauchy pass from local to global information; L’Hôpital is a corollary of Cauchy. The point cc exists, need not be unique and is almost never calculated.
  • Lip(f)=sup⁡∣f′∣\mathrm{Lip}(f) = \sup\abs{f'} on an interval: 1/41/4 for the sigmoid, 11 for tanh, softplus and ReLU, ≈1.129\approx 1.129 for GELU. Constants multiply under composition, and the bound is not exact. x\sqrt{x} is not Lipschitz but is 1/21/2-Hölder.
  • Difference quotients have error O(h)\bigO(h) (forward) or O(h2)\bigO(h^2) (central) plus roundoff ∼u∣f∣/h\sim u\abs{f}/h: in float64, h≈10−8h \approx 10^{-8} and h≈10−5h \approx 10^{-5}.