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.
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 ⌈log2((b−a)/tol)⌉ steps, no more. That count follows from a proof, not an experiment: the intermediate value theorem.
Counterexamples. Function sin(1/x) equals 0 at all x=1/(nπ) and 1 at all x=1/(π/2+2nπ). 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∣, perturbing input by δ moves output by at most Lδ. 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/4, tanh 1) 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). Choosing h requires understanding opposing errors: Taylor error favors small h, while rounding penalizes it.
One idea unifies the lesson: the derivative is the best linear approximation to f near a point, with error 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) with a matrix.
A limit as a game between adversaries
“f(x) tends to L as x tends to a” 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 ε and δ form.
Read it as a two-player game. The adversary chooses arbitrarily demanding tolerance ε>0. You respond with radius δ>0, possibly depending on ε. You win if every domain x within δ of a, excluding a itself, satisfies ∣f(x)−L∣<ε. The limit is L if you have a winning strategy: an answer for every ε.
Three details matter and appear in the figure:
x=a does not count (0<∣x−a∣). A limit concerns behavior neara, not ata; f need not be defined at a and may have any value there.
Quantifier order matters.∀ε∃δ lets δ depend on ε. Reversing order to ∃δ∀ε asserts one δ works for every tolerance, forcing f to equal constant L near a (possibly except at a).
Any one δ suffices, not the best. If δ works, any δ′<δ also works.
InteractiveThe ε–δ game
f(x)=x2
band ∣y−L∣<ε
band 0<∣x−a∣<δ
points outside the box
∀x:0<∣x−1∣<0.300⇒∣f(x)−1.00∣<0.500×
View
sup∣f(x)−L∣ in the band0.690
Maximum δ for this ε0.225
δmax/ε0.450
Rounds wonnone
You lose: x=1.30 lies in the vertical band and ∣f(x)−L∣=0.690≥ε. Some δ work: any below 0.225.
The horizontal band is ∣y−L∣<ε (adversary tolerance) and vertical band 0<∣x−a∣<δ (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 x2 always win: press ‘Next round’ several times and watch δmax/ε approach 1/2. Then try the jump and sin(1/x): move L anywhere and find ε for which no δ exists. For Thomae’s function the natural candidate L=f(1/2)=1/2 loses; which L wins?
For f(x)=x2 at a=1, the largest δ working for each ε is δmax=1+ε−1 (the vertical band first hits the box above, where the parabola rises faster). For ε=0.5 it is 0.2247, and as ε→0, δmax/ε→1/2. That 1/2 is 1/f′(1): slope of f 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 δ as a function of ε and verification it works. The task is always the same: bound ∣f(x)−L∣ by something depending only on ∣x−a∣.
When f is less friendly, bound in two stages: first restrict δ≤1 to control factors not tending to zero, then adjust the remainder. The first exercise does this for limx→2x2=4, choosing δ=min(1,ε/5).
Negating the definition: when no limit exists
To prove a limit is notL, negate its definition. By quantifier laws, every ∀ becomes ∃ and vice versa, while implication P⇒Q becomes P∧¬Q:
x→alimf(x)=L⟺∃ε>0∀δ>0∃x∈D:0<∣x−a∣<δ∧∣f(x)−L∣≥ε.
In the game, the adversary has one move, an ε, against which every response loses. For each δ a witnessx in the vertical band lies outside the box. The figure’s panel displays this when no δ exists.
The example illustrates a general nonexistence pattern: two sequences tending to a whose images tend to different values. The next theorem makes this exact and works in the other direction too.
Proof
(⇒) Given ε take the definition’s δ. Since xn→a (sequence limits are reviewed in lesson 3), some N satisfies ∣xn−a∣<δ for n≥N, and since xn=a, also 0<∣xn−a∣. Thus ∣f(xn)−L∣<ε for n≥N.
(⇐) By contrapositive, suppose the limit is not L. Negation gives ε>0 such that for each δ=1/n some xn∈D satisfies 0<∣xn−a∣<1/n and ∣f(xn)−L∣≥ε. This sequence tends to a, excludes a and f(xn) does not tend to L.
∎
Notice “every.” Checking one sequence, ten, or regular samples proves nothing: f(1/(nπ))=0 for every n yet sin(1/x) has no limit. The reverse direction therefore uses definition negation, not experiments.
Uniqueness and limit algebra
Proof
By contradiction, suppose L=M and take ε=∣L−M∣/2>0. Each limit gives δ1 and δ2; with δ=min(δ1,δ2) and x∈D satisfying 0<∣x−a∣<δ (exists since a is an accumulation point), ∣L−M∣≤∣L−f(x)∣+∣f(x)−M∣<2ε=∣L−M∣. Contradiction.
∎
This explains requiring a to be an accumulation point: without points of D near a, the defining implication would hold vacuously for every L.
Calculation rules are as expected: if f→L and g→M at a, then f+g→L+M, fg→LM and, if M=0, f/g→L/M. The sum uses triangle inequality with ε/2 per term. Product adds and subtracts:
∣f(x)g(x)−LM∣≤∣f(x)∣∣g(x)−M∣+∣M∣∣f(x)−L∣,
together with boundedness of f near a (with ε=1, ∣f(x)∣<∣L∣+1). Quotient also needs g bounded away from 0, guaranteed by M=0: near a, ∣g(x)∣>∣M∣/2.
Continuity and the intermediate value theorem
If a is an accumulation point of D, this is equivalent to limx→af(x)=f(a): the limit exists and equals the value. If a is isolated in D, f is automatically continuous at a (take δ below the distance to other points). By sequential characterization, f is continuous at a iff xn→a implies f(xn)→f(a): continuous functions commute with limits, f(limxn)=limf(xn).
Limit algebra yields continuity algebra: sums, products and quotients (where the denominator is nonzero) of continuous functions are continuous. Polynomials, exp, sin and cos are continuous on R, and log on (0,∞). Composition remains, with a two-line proof and a lesson.
Proof
Given ε, continuity of f at b=g(a) gives η>0 with ∣y−b∣<η⇒∣f(y)−f(b)∣<ε. Continuity of g at a with tolerance η gives δ with ∣x−a∣<δ⇒∣g(x)−b∣<η. Chaining gives ∣x−a∣<δ⇒∣f(g(x))−f(b)∣<ε.
∎
The lesson: one layer’s tolerance is the ε 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. Function f(x)=x2−2 is continuous on [0,2]∩Q, changes sign and vanishes at no rational. The issue is holes in Q; proof must use real completeness. We give an algorithmic proof.
Proof
It suffices to consider f(a)<0<f(b) (for general y apply to f−y; for reversed signs use −f). Construct intervals [an,bn] with a0=a, b0=b: if m=(an+bn)/2 satisfies f(m)<0 take [an+1,bn+1]=[m,bn]; otherwise [an,m]. By construction f(an)<0≤f(bn) for every n, sequence (an) increases, (bn) decreases, and bn−an=(b−a)/2n.
A bounded monotone sequence converges (completeness), so an→c and bn→c′; since bn−an→0, c=c′. Continuity gives f(c)=limf(an)≤0 and f(c)=limf(bn)≥0. Hence f(c)=0.
∎
The proof is the bisection method and gives its guarantee. After n steps root c lies in [an,bn], length (b−a)/2n, so any point in the interval is at most (b−a)/2n from a root. To guarantee error ≤tol, use
n=⌈log2tolb−a⌉
iterations plus initial evaluations at a and b. This worst-case bound is independent of f: bisection always gains one bit per evaluation. Newton is far faster when f is smooth but convergence has caveats (good starting point, 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 a 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+) is a jump of size f(a+)−f(a−). The figure’s jump has f(0−)=0 and f(0+)=1; 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} is bounded above by f(c), so has supremum s≤f(c) (completeness again). Given ε, supremum gives x0<c with f(x0)>s−ε, and for x0<x<c monotonicity gives s−ε<f(x0)≤f(x)≤s. With δ=c−x0 obtain f(c−)=s. The right side is symmetric using infimum.
If f is discontinuous at c, then f(c−)<f(c+) and open interval (f(c−),f(c+)) is nonempty: choose rational qc inside. For c<c′ intervals do not overlap because f(c+)≤f(x)≤f(c′−) for any x between c and c′. Thus c↦qc injects discontinuities into countable 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−n over an enumeration of Q), but never behave like sin(1/x).
Landau notation: little o and big O
When approximations are chained, writing ε and δ at each step is unbearable. Landau notation packages the limit definition into a symbol.
Thus o(1) means “something tending to 0,” o(h) means “something tending to 0 faster than h,” and O(h2) means “something bounded by a multiple of h2.” Useful examples as h→0:
And as n→∞: nlogn=o(n2), n100=o(2n), logn=o(nα) for every α>0. The latter is algorithmic asymptotic notation; h→0 describes approximation errors and governs this lesson.
Calculation rules for h→0 and m,n≥0 follow directly from the definition:
o(hn)+o(hn)=o(hn) and c⋅o(hn)=o(hn) for every constant c. Likewise for O.
hm⋅o(hn)=o(hm+n), O(hm)⋅o(hn)=o(hm+n) and O(hm)⋅O(hn)=O(hm+n).
o(hn)⊂O(hn) and O(hn+1)⊂o(hn): higher order is smaller.
If φ(h)=O(h) and ρ(k)→0 as k→0 with ρ(0)=0, then ρ(φ(h))φ(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 a and a+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)/h for h=0; the condition is exactly r(h)→0. Since r(h)=hf(a+h)−f(a)−m, the difference quotient tends to m iff r(h)→0. This proves equivalence with m=f′(a). For uniqueness, if m1 and m2 both satisfy it, subtraction gives (m1−m2)h=o(h), i.e. m1−m2=o(h)/h→0: constant m1−m2 is therefore zero.
∎
The geometry is literal. In a half-width-w window centered at (a,f(a)), vertical distance between graph and line f(a)+mh at x=a+h in window units is ∣h∣∣r(h)∣/w≤∣r(h)∣; at the edge ∣h∣=w it is exactly ∣r(h)∣. Maximum visible deviation is thus order sup0<∣h∣≤w∣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)=sinx+x2/4,r(h)=hf(a+h)−f(a)−mh
Relative error r(h) versus scale ∣h∣ (logarithmic)
f
line f(a)+mh
r(h), h>0
r(h), h<0
window scale
f′(a)1.0967
Half-width w0.20
Deviation sup0<∣h∣≤w∣r(h)∣0.026
Keep zooming: deviation in window widths is sup∣r(h)∣ and tends to 0.
Top: half-width w window about (a,f(a)) with candidate slope m; bottom: relative error r(h) versus ∣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 m: error tends to f′(a)−m, not zero. Then try ∣x∣ at a=0 (the cusp never flattens), x2sin(1/x) (always oscillates yet flattens) and xsin(1/x) (does not flatten). What happens to ∣x∣ if a moves away from 0?
Differentiation rules, one by one
Form f(a+h)=f(a)+f′(a)h+o(h) turns derivative rules into Landau algebra. Write f=f(a), f′=f′(a) and likewise for g.
It fails if g(a+h)=g(a) for values of h arbitrarily close to 0, and that happens: g(x)=x2sin(1/x) vanishes at every x=1/(nπ). The version with o(h) avoids the problem without ever dividing.
k(h)=g(a+h)−g(a)=g′(a)h+o(h)=O(h)
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) and 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 f is differentiable at a, then f(a+h)−f(a)=f′(a)h+o(h)→0: f is continuous at a. You will prove this step by step in the exercises. The converse fails in instructive ways:
∣x∣ and ReLU at 0. They are continuous, but the one-sided slopes differ: limh→0±∣h∣/h=±1 for ∣x∣, and 1 and 0 for ReLU. In the figure, the peak looks the same at every scale, because ∣x∣ is invariant under scaling. No m makes r(h)→0 on both sides.
xsin(1/x) at 0 (with value 0 at 0). Continuous, and the difference quotient is sin(1/h), which has no limit. Zooming in reproduces the fan of oscillations between the lines y=±x at every scale.
x2sin(1/x) at 0 (with value 0 at 0). Here the quotient is hsin(1/h)→0, so it is differentiable with f′(0)=0, although it oscillates infinitely often near 0. But for x=0, f′(x)=2xsin(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 C1, strictly smaller than the class of differentiable functions.
3x at 0. The quotient is h−2/3→+∞: a vertical tangent, which is not an approximation of the form f(a)+mh.
It can be much worse: in 1872 Weierstrass presented (published in 1875) a function continuous on all of R and differentiable nowhere, ∑nancos(bnπx) with 0<a<1, b an odd integer and ab>1+3π/2 (Hardy proved in 1916 that ab≥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 to 1, is not the derivative of any function on 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 f 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>0, f(c+h)−f(c)≤0, so the difference quotient is ≤0 and so is its right-hand limit, f′(c). For h<0 the quotient is ≥0 and the left-hand limit, which is the same f′(c), is ≥0. Hence f′(c)=0.
∎
Proof
By Weierstrass, f attains on [a,b] a maximum M and a minimum m. If both are attained at the endpoints, M=m=f(a) and f is constant: any c works. Otherwise one is attained at an interior point c, and by Fermat f′(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,b−af(b)−f(a)=1.000
f′(x) on (a,b) and secant slope: each crossing is a c
f
secant
parallel tangents and f′
a, b−2.00, 2.00
Secant slope1.0000
Points c with matching f′(c)−1.155, 1.155
2 points c: the theorem guarantees at least one, not exactly one.
Drag the endpoints a and b along the graph. The secant is violet; in magenta, the tangent at each c with f′(c) equal to its slope. Below, f′ on (a,b) and the horizontal line at that slope: the c are the intersections. For the cubic there are two; for the wave, several; for the parabola, always the midpoint. For ∣x∣ on [−1,2] there are none: which assumption fails, and what does f′ do in the lower graph? With x, move a to 0.
Three lessons from the figure. The theorem gives existence, not uniqueness: x3−3x on [−2,2] has a secant of slope 1 and f′(c)=3c2−3=1 at c=±2/3≈±1.1547. In general c cannot be calculated: it is a root of f′(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 on [0,4] satisfies the theorem (c=1) even though f′(0) does not exist; but a single interior point without a derivative suffices to break it, as with ∣x∣, whose derivative jumps from −1 to 1 without taking the value 1/3.
The consequences are used every day:
If f′=0 on an interval, f is constant on it. (Apply the theorem between any two points.)
If f′≥0 on an interval, f is increasing; if f′>0, strictly increasing.
If ∣f′∣≤L on an interval, then ∣f(x)−f(y)∣≤L∣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) is continuous on [a,b], differentiable on (a,b) and satisfies φ(a)=f(b)g(a)−g(b)f(a)=φ(b). Rolle gives a c with φ′(c)=0, which is the claim.
∎
Geometrically, the curve t↦(g(t),f(t)) has a tangent parallel to the chord between its endpoints at some point. Taking g(x)=x recovers Lagrange. And Cauchy’s theorem yields L’Hôpital’s rule almost for free.
Proof
Redefine f(a)=g(a)=0, making them continuous at a. For nearby x>a, Cauchy’s theorem on [a,x] gives a cx∈(a,x) with f(x)g′(cx)=g(x)f′(cx). Also g(x)=0: if g(x)=g(a)=0, Rolle would give a point between a and x with g′=0. Thus f(x)/g(x)=f′(cx)/g′(cx). When x→a+, also cx→a+, and the quotient tends to ℓ. The left-hand case is the same.
∎
For example, applying it three times, limx→0x3x−sinx=lim3x21−cosx=lim6xsinx=61, another way of saying sinx=x−x3/6+o(x3). The rule gives a sufficient, not necessary, condition: xx+sinx→1 as x→∞, while the quotient of derivatives, 1+cosx, has no limit. If 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 ε there is a δ, but does not say which one, and that δ 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 works at every point at once (a special case of uniform continuity in lesson 5). Geometrically, fixing a point (x0,f(x0)) on the graph, the condition says the graph never enters the vertical double cone ∣y−f(x0)∣>L∣x−x0∣. The Lipschitz constant is the slope of the widest cone that can slide along the whole graph without touching it.
Proof
(≤) For x<y in I, the mean value theorem gives a c∈(x,y) with ∣f(y)−f(x)∣=∣f′(c)∣∣y−x∣≤sup∣f′∣∣y−x∣. (≥) For interior x, ∣f′(x)∣=limy→x∣f(y)−f(x)∣/∣y−x∣, and each quotient is ≤Lip(f), so the limit is too.
∎
InteractiveThe Lipschitz cone
∣f′(x)∣ and level L: red shows where ∣f′∣>L
f
forbidden cone ∣y−f(x0)∣>L∣x−x0∣
∣f′∣
Minimum L for this vertex0.204
Record while moving the vertex0.204
sup∣f′∣ (theory)0.250
L≥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∣; portions of the graph entering it are marked red. Below are ∣f′∣ and the level L. With the sigmoid, lower L until some vertex fails and press ‘Sweep vertex’: the record for the minimum L per vertex stops at sup∣f′∣=1/4, and every vertex placed where ∣f′∣>L fails. Repeat with tanh, softplus and GELU. With x, move the vertex to 0: is there any L that works?
With the theorem, each activation’s constant follows in one line:
Activation
Derivative
sup∣f′∣
Where
Sigmoid σ(x)=1/(1+e−x)
σ(1−σ)
1/4
at x=0, where σ=1/2
tanh
1−tanh2
1
at x=0
Softplus log(1+ex)
σ(x)
1
not attained: σ<1
ReLU
0 or 1 (does not exist at 0)
1
directly: ∣max(0,x)−max(0,y)∣≤∣x−y∣
GELU xΦ(x)
Φ(x)+xφ(x)
Φ(2)+e−1/π≈1.129
at x=2
The sigmoid’s is the product p(1−p) with p∈(0,1), maximized at p=1/2. GELU’s follows by setting dxd(Φ+xφ)=φ(x)(2−x2) 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∣, so
Lip(f∘g)≤Lip(f)Lip(g).
Two consequences for networks. A chain of n sigmoids has derivative bounded by 4−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: σ∘σ has constant 0.0590, not 1/16=0.0625, because the point where σ 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 on [0,1] is continuous (even uniformly) but not Lipschitz: with y=0, x/x=1/x→∞. What it does satisfy is a weaker inequality.
With α=1 it is Lipschitz; the smaller α is, the sharper the function may be at small scales, because ∣x−y∣α≫∣x−y∣ when ∣x−y∣ is small. The square root is 1/2-Hölder on [0,∞) with C=1: for x≥y≥0, (y+x−y)2=x+2y(x−y)≥x, hence x−y≤x−y. Similarly xα is α-Hölder. On bounded intervals, if β<α, every α-Hölder function is β-Hölder, giving a scale of regularity:
C1 en [a,b]⇒Lipschitz⇒α-Ho¨lder⇒uniformemente continua⇒continua.
The first implication uses that f′ continuous on a compact set is bounded. No arrow reverses: ∣x∣ is Lipschitz and not C1, x is Hölder and not Lipschitz, and 1/log(1/x) on (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, α-Hölder on every bounded interval for every α<1/2 and for no α≥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−5 is the one Wallis used to illustrate Newton’s method in the seventeenth century. And with 1/x bisection calmly returns a point 1.5×10−11 from the pole, where ∣f∣ is almost 7×1010: 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 f is sufficiently differentiable,
In the central quotient the even terms cancel, and the truncation error goes from O(h) to O(h2). 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), but its rounded value, with relative error up to u=2−53≈1.1×10−16 (unit roundoff, half the machine epsilon). Subtracting f(a+h)−f(a) two nearly equal numbers preserves their absolute error, of order u∣f(a)∣, but not their magnitude: this is catastrophic cancellation. Divided by h, the roundoff error is of order u∣f(a)∣/h and grows as h decreases. Adding the two and minimizing, the optimal h is of order u≈10−8 for the forward quotient and u1/3≈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−8 with error about 10−9 (half the float64 digits); for the central quotient, around h≈10−5 with error about 10−13. With h=10−12, so small that it seems “more accurate”, the forward error is 4×10−5: four orders of magnitude worse than with h=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 h, both axes logarithmic
forward hf(a+h)−f(a)
centered 2hf(a+h)−f(a−h)
models
f(a + h) =
f(a) =
Exact 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∗ (forward)2 × 10⁻⁸
Model h∗ (centered)8 × 10⁻⁶
Truncation region for both: forward-difference error falls as h (slope 1), centered error as h2 (slope 2), as Taylor predicts.
Absolute error versus h, 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)∣/h with noise. Move h to 10−12 and look at the strip of digits: f(a+h) and f(a) share almost all their digits, which are crossed out in the subtraction. Switch to 1/x at a=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−6 by default and warns if inputs are not double precision: in float32, with u≈6×10−8, the minimum central quotient error is around u2/3≈10−5 relative, too much to distinguish a correct gradient from a slightly wrong one. The full analysis, including the optimal choice of h and the effect of rounding a+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) on a grid is f′(ξi) for some ξi, so their maximum is a lower bound on sup∣f′∣ that converges to it as the grid is refined, if 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.25, 1, almost 1 for softplus (at [−10,10] the maximum derivative is σ(10)≈0.99995), 1 and 1.1289. The composition of two sigmoids gives 0.05896, below the bound 1/16. And for x the maximum is the first quotient, 1/n/(1/n)=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) at 0 comes out as AccumBounds(-1, 1), SymPy’s way of saying that values accumulate throughout [−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 σ′ and tanh′, at x=0, with exact values 1/4 and 1; for GELU, the points ±2 and value 21+21erf(1)+e−1/π, which agrees with the grid estimate to all the digits it can give. Note that maximizing ∣f′∣ also requires checking interval endpoints and behavior at infinity; here f′ tends to constants (0 or 1) that do not exceed the interior maximum, except for softplus, where the supremum 1 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:
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 f 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: limx→2x2=4.
0
Let ε>0. Find δ>0 such that 0<∣x−2∣<δ implies ∣x2−4∣<ε.
Step 1 of 3. How do you start bounding x2−4?
NumericThe largest δ
For f(x)=x2 at a=1 with L=1 and ε=0.5, what is the largest δ such that 0<∣x−1∣<δ implies ∣x2−1∣<0.5?
QuizNegating the definition
Which formula expresses that limx→af(x)=L?
ProofDifferentiability implies continuity
Prove: If f is differentiable at a, then f is continuous at a. The converse is false.
0
Let f be differentiable at a, with derivative f′(a).
Step 1 of 3. What exactly must be proved?
NumericThe sigmoid constant
Calculate the optimal Lipschitz constant on R of the sigmoid σ(x)=1/(1+e−x).
QuizWhich are Lipschitz on [0, 1]?
Which of these functions are Lipschitz on [0,1]? For xsin(1/x), take the value 0 at x=0.
More than one answer may be correct.
NumericThe product bound is not exact
Calculate Lip(σ∘σ)=supx∣σ′(σ(x))σ′(x)∣ to four significant figures. The product bound gives 1/4⋅1/4=0.0625.
NumericHow many bisections?
A continuous function changes sign on [1,2]. How many bisection iterations (excluding the two initial evaluations) guarantee finding a root with error at most 10−6?
NumericA 0/0 limit
Calculate limx→0x3tanx−x.
QuizLandau rules
As h→0, which statements are true?
More than one answer may be correct.
QuizThe best h
You approximate f′(1) with f=sin in float64 using the central quotient (f(1+h)−f(1−h))/(2h). Which of these h gives the smallest error?
ProofThe mean value theorem from Rolle
Prove: If f is continuous on [a,b] and differentiable on (a,b), there exists c∈(a,b) with f′(c)=b−af(b)−f(a).
0
Call s=b−af(b)−f(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 m with f(a+h)=f(a)+mh+o(h): in that form the differentiation rules are Landau algebra and the mean value theorem turns bounds on f′ into global guarantees, such as Lipschitz constants.
limx→af(x)=L means ∀ε∃δ∀x(0<∣x−a∣<δ⇒∣f(x)−L∣<ε). Negate it by changing each quantifier and exhibiting a witness for each δ; it is equivalent to f(xn)→L for every sequence xn→a with xn=a.
Continuous functions commute with limits and compose. Bolzano’s theorem needs completeness of R and its proof is bisection, with ⌈log2((b−a)/tol)⌉ guaranteed iterations.
Monotone functions have one-sided limits at every point; their discontinuities are jumps and form an at most countable set.
o(h) and O(h) package ε and δ; the Landau equals sign denotes membership.
Differentiability implies continuity, not conversely (∣x∣, ReLU, xsin(1/x)); moreover a derivative can exist everywhere without being continuous (x2sin(1/x)). The chain rule is proved without dividing by 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 c exists, need not be unique and is almost never calculated.
Lip(f)=sup∣f′∣ on an interval: 1/4 for the sigmoid, 1 for tanh, softplus and ReLU, ≈1.129 for GELU. Constants multiply under composition, and the bound is not exact. x is not Lipschitz but is 1/2-Hölder.
Difference quotients have error O(h) (forward) or O(h2) (central) plus roundoff ∼u∣f∣/h: in float64, h≈10−8 and h≈10−5.