The Riemann integral and the fundamental theorem of calculus
A review of the Riemann integral through Darboux sums, both parts of the fundamental theorem of calculus, frequently used integration techniques (substitution and parts), and improper integrals, with the Gamma function as a first serious example. Convergence of improper integrals is emphasized because it determines whether expectations and moments exist.
After this lesson you can
Define the Riemann integral using Darboux sums and decide integrability of monotone, continuous and pathological functions.
Prove the fundamental theorem of calculus and use it to relate accumulation to rate of change.
Apply substitution and integration by parts while controlling boundary terms.
Determine convergence of improper integrals by comparison with powers and exponentials.
Define the Gamma function, prove Γ(n + 1) = n!, and recognize it in power-times-exponential integrals.
Motivation: almost everything continuous is an integral
In machine learning and probability, the integral appears before any other calculus tool, almost always in disguise:
Expectations. If X has density p, E[f(X)]=∫f(x)p(x)dx. Expected loss, risk R(θ)=E[ℓ(fθ(X),Y)], is an integral; empirical loss is a sum approximating it. Whether an expectation exists is a question about convergence of an improper integral, and the answer is not always yes: the Cauchy distribution has no mean.
Normalization constants. A density is a nonnegative function divided by its integral. The normal has 2π, the Gamma family has Γ(α), and in energy-based models, pθ(x)=e−Eθ(x)/Z(θ), all the difficulty lies in Z(θ)=∫e−Eθ(x)dx.
Accumulation. Distribution function F(x)=P(X≤x) accumulates the density, and density is the rate of change of F. This pair, accumulation and differentiation, is the fundamental theorem of calculus.
Sums and integrals at once. A variable that is 0 with probability 0.3 and otherwise exponential has no density and is not discrete. Its expectation is neither a sum nor a Riemann integral, but is ∫fdF, a Riemann–Stieltjes integral.
This lesson reviews the single-variable Riemann integral with the rigor needed to trust it: when it exists, why the derivative of accumulation is the integrand, how to manipulate it (substitution and parts, without losing boundary terms), when an improper integral converges and how one formula unifies sums and integrals. It ends with function Γ, appearing in every moment, volume and normalization in the rest of the course. It uses continuity, the derivative and the mean value theorem from the preceding lesson.
Intuition: trapping area between two staircases
To measure area under a positive curve f on [a,b], cut it into vertical strips. In each strip, the rectangle of height equal to the minimum of f fits under the curve, and the rectangle of height equal to the maximum contains it. The sum of the first gives a lower approximation; the second, an upper one. If refining the strips brings the staircases arbitrarily close, the area is trapped between them and its value is unambiguous. If they do not approach, “area” has no unique meaning.
InteractiveDarboux sums closing in
lower sum L: rectangles of height mi
U−L: bands between mi and Mi
U−L with n equal subintervals (logarithmic scales)
U − L, uniform partition
reference 1/n
Partition
Subintervals6
Mesh ∥P∥0.1667
Lower sum L(f,P)0.4623
Upper sum U(f,P)0.6877
U−L0.2254
∫01f0.5750
Continuous on [0,1], hence uniformly continuous: on short intervals Mi−mi is simultaneously small and U−L→0.
Blue rectangles are the lower sum, height mi=inff on each subinterval; orange strips run from mi to Mi=supf, so their total area is exactly U−L. Increase n with the continuous function and watch orange vanish. In free mode, drag points or press ‘Refine where most is contributed’ and check refinement never increases U−L. Then try Dirichlet's function (does orange decrease at all?), Thomae's, discontinuous at every rational, and sin(1/x). The lower graph shows U−L versus n on logarithmic axes: the monotone function's slope is that of 1/n.
Four things the figure shows and the rest of the section turns into theorems:
Refining always helps. Adding a partition point never lowers the lower sum or raises the upper sum.
Rate depends on the function. For the continuous and monotone functions, U−L falls like 1/n: the logarithmic graph’s slope is −1.
Some functions cannot be trapped. With the rational indicator, every subinterval contains rationals and irrationals, so Mi=1 and mi=0 for any partition. Orange always fills everything.
But many discontinuities do not suffice to prevent it. Thomae’s function jumps at every rational and still U−L→0, though more slowly than 1/n. With sin(1/x), discontinuous only at 0, the gap also closes, but at rate 1/n (slope −1/2): near 0, about n/2π subintervals contain a complete oscillation and each contributes the full amplitude.
Darboux sums
Let f:[a,b]→R be bounded. A partition of [a,b] is a finite set P={x0,x1,…,xn} with a=x0<x1<⋯<xn=b. Write Δxi=xi−xi−1 and call the mesh of P the quantity ∥P∥=maxiΔxi. On each subinterval,
which exist because f is bounded. The lower and upper Darboux sums are
L(f,P)=i=1∑nmiΔxi,U(f,P)=i=1∑nMiΔxi.
A partition Q is a refinement of P if P⊆Q.
Proof
Adding one point suffices, because Q is obtained from P by adding points one at a time. Let y∈(xk−1,xk). On each half, the infimum of f is at least mk, being an infimum over a smaller set. Calling those infima m′ and m′′, mkΔxk=mk(y−xk−1)+mk(xk−y)≤m′(y−xk−1)+m′′(xk−y), and other terms do not change: L does not decrease. The argument for U is the same with suprema. The middle inequality, L(f,Q)≤U(f,Q), is mi≤Mi term by term. For the consequence, take the common refinement Q=P1∪P2: L(f,P1)≤L(f,Q)≤U(f,Q)≤U(f,P2).
∎
Thus any lower sum lies below any upper sum. The supremum of the former and infimum of the latter exist and satisfy
∫abf=PsupL(f,P)≤PinfU(f,P)=∫abf.
Comparing infima and suprema over all partitions is cumbersome. The following criterion reduces integrability to finding one good partition for each tolerance, as you did in the figure.
Proof
If such a partition exists for every ε, then 0≤∫f−∫f≤U(f,P)−L(f,P)<ε for every ε>0, and the two integrals agree. Conversely, if they agree and equal I, by definition of supremum and infimum there are partitions P1 and P2 with L(f,P1)>I−ε/2 and U(f,P2)<I+ε/2. Their common refinement P satisfies, by the lemma, U(f,P)−L(f,P)≤U(f,P2)−L(f,P1)<ε.
∎
Riemann sums and mesh
Riemann’s sums choose a point ti∈[xi−1,xi] in each subinterval (a tag; the partition is a tagged partition) and evaluate the function there:
S(f,P,t)=i=1∑nf(ti)Δxi.
Since mi≤f(ti)≤Mi, always L(f,P)≤S(f,P,t)≤U(f,P): Riemann sums are trapped between Darboux sums, whatever the tag. Midpoint, trapezoid and Simpson rules are sums of this kind (or averages of them), so every quadrature method starts here (Newton–Cotes rules). The practical question is whether making the mesh small suffices, without worrying where points fall.
Proof
If Riemann sums converge to I in that sense, take P with ∥P∥<δ. Choosing tags where f is within ε/(b−a) of Mi gives U(f,P)≤S+ε≤I+2ε, and similarly L(f,P)≥I−2ε, so U−L≤4ε and f is integrable by the criterion, with integral I.
Conversely, let ∣f∣≤K with K>0 and let ε>0. By the criterion there is a partition P0 with U(f,P0)−L(f,P0)<ε/2; let k≥1 be its interior points (if none, add one: by the lemma refinement does not increase the gap). Take δ=ε/(8Kk) and a partition P with ∥P∥<δ. Passing from P to P∪P0, only subintervals of P containing some point of P0 in their interior change, at most k of them; in each the upper sum changes by at most 2KΔxi<2Kδ. Therefore U(f,P)≤U(f,P∪P0)+2Kkδ and, similarly, L(f,P)≥L(f,P∪P0)−2Kkδ. Using the lemma,
U(f,P)−L(f,P)≤U(f,P0)−L(f,P0)+4Kkδ<2ε+2ε=ε.
Since S(f,P,t) and I both lie in [L(f,P),U(f,P)], ∣S(f,P,t)−I∣<ε.
∎
Which functions are integrable
Proof
(1) If f is increasing, on [xi−1,xi] the infimum is f(xi−1) and supremum f(xi), wherever jumps occur. Then
because the sum telescopes; with Δxi=(b−a)/n the inequality is equality. If f is decreasing, apply the above to −f.
(2) A continuous function on a closed bounded interval is uniformly continuous (Heine–Cantor theorem): given ε>0 there is δ>0 such that ∣x−y∣<δ implies ∣f(x)−f(y)∣<ε/(b−a), the same δ for every point. If ∥P∥<δ, on every subinterval Mi−mi≤ε/(b−a), and U−L≤∑iεΔxi/(b−a)=ε.
∎
The first part is more useful than it looks: it gives a certificate. For a monotone function, the true integral lies in [L,U] and that interval has exact length ∣f(b)−f(a)∣(b−a)/n, with no unknown constants. You will implement this below. The second explains why uniform continuity is needed: with f continuous on (0,1] but unbounded, like 1/x, no partition works, because the first subinterval has M1=∞.
The same argument extends to bounded functions with finitely many discontinuities: surround each by an arbitrarily short subinterval, whose contribution to U−L is at most 2sup∣f∣ times its length, and use uniform continuity on the rest. This integrates sin(1/x) on [0,1], which oscillates infinitely often but is discontinuous only at 0. Infinitely many discontinuities require closer examination.
The difference is not the number of discontinuities but their “size.” The exact result is Lebesgue’s.
Every countable set has measure zero (cover its k-th point by an interval of length ε/2k+1), so Thomae, discontinuous on Q, is integrable, and Dirichlet, discontinuous everywhere, is not. There are also uncountable measure-zero sets, such as the Cantor set, and the Cantor set’s indicator is integrable with integral 0. The proof of the criterion and the theory resolving Dirichlet’s case (it is Lebesgue integrable with integral 0) are in the Lebesgue integral, built on Lebesgue measure.
Properties used without thinking
For f and g integrable on [a,b] and c∈(a,b), all follow from Darboux sums:
Linearity:∫(αf+βg)=α∫f+β∫g.
Monotonicity: if f≤g, ∫f≤∫g. In particular, ∫f≤∫∣f∣≤(b−a)sup∣f∣, because ∣f∣ is also integrable (Mi−mi does not increase on taking absolute value).
Additivity:f is integrable on [a,c] and [c,b], and ∫abf=∫acf+∫cbf. With the orientation convention, the formula holds for a,b,c in any order.
Products and compositions:fg is integrable, and φ∘f also if φ is continuous.
Changing f at finitely many points does not change the integral (or integrability).
Proof
By the extreme value theorem, f attains a minimum m and maximum M, and by monotonicity m(b−a)≤∫abf≤M(b−a). Number b−a1∫abf lies between m and M, and by the intermediate value theorem is a value f(c).
∎
The fundamental theorem of calculus
So far integration is a limiting process: no formula. What makes the integral calculable is that accumulation and differentiation are inverse operations. If f is integrable on [a,b], the indefinite integral
F(x)=∫axf(t)dt,x∈[a,b],
measures signed area accumulated up to x. Its increment between x and x+h is the area of a narrow strip, F(x+h)−F(x)=∫xx+hf, and if f barely changes on the strip, that area is nearly f(x)h. Dividing by h: the rate at which area grows is curve height.
InteractiveAccumulation and rate
Integrand f and signed area accumulated over [0,x]
Accumulated area F(x)=∫0xf(t)dt and its slope
positive area
negative area
height f(x) and tangent of slope f(x)
strip [x,x+h] and its secant
x1.20
F(x)=∫0xf1.8299
Height f(x)1.0070
hF(x+h)−F(x)0.7563
Where f<0 area counts negatively and F decreases. Maxima of F occur where f changes sign from + to −.
Above, f and signed area accumulated at [0,x] (blue if f>0, red if f<0); below, curve F(x)=∫0xf traced by that area, with tangent of slope f(x) in magenta. The gold strip has area F(x+h)−F(x) and its height is the difference quotient. Drag x or press ‘Traverse’ and compare readouts of f(x) and the quotient; then reduce h. Choose the jump function and move x to 2: F has a peak and two one-sided slopes. With the function changed at one point, F does not notice. With the peak, F is differentiable everywhere with F′=f: it is class C1, with no corners.
These two statements, the derivative of accumulation is the integrand and the integral of a derivative is the increment, are the fundamental theorem of calculus. The Lipschitz bound in part 1 is immediate: ∣F(y)−F(x)∣=∫xyf≤K∣y−x∣. You will prove the derivative at a continuity point in a guided exercise, using the strip argument.
ProofProof of part 2
Let P be any partition of [a,b]. By the mean value theorem applied to G on each [xi−1,xi], there is ti∈(xi−1,xi) with G(xi)−G(xi−1)=G′(ti)Δxi=f(ti)Δxi. Summing, the telescoping sum gives
G(b)−G(a)=i=1∑nf(ti)Δxi=S(f,P,t),
which lies between L(f,P) and U(f,P). Thus G(b)−G(a) lies between L(f,P) and U(f,P) for every partition; since f is integrable, the only number with that property is ∫abf.
∎
Notice what part 2 does not require: f need not be continuous, only integrable, and G differentiable throughout the interior with G′=f. The two assumptions are independent and neither can be omitted:
Integrable without an antiderivative. An f with a jump, like the figure’s, is integrable but is not the derivative of any function on the entire interval: by Darboux’s theorem every derivative has the intermediate value property, which a jump function lacks. Its indefinite integral F exists, is continuous and has a corner at the jump, with one-sided derivatives f(c−) and f(c+); in the figure, since slope passes from positive to negative, the corner is also a peak.
Antiderivative without integrability.G(x)=x2sin(1/x2), with G(0)=0, is differentiable on all R, but G′(x)=2xsin(1/x2)−(2/x)cos(1/x2) is unbounded near 0, so G′ is not Riemann integrable on [0,1]. Formula ∫01G′=G(1)−G(0) still holds as an improper integral, but not as a Riemann integral.
And notice the figure’s third option: f(x)=1.4−0.9∣x−2∣ is not differentiable at 2, but is continuous, so F′=f everywhere and F is class C1. Integrating smooths by one degree; differentiating removes one. Thus accumulation of noise (a random path, a sum of errors) is more regular than the noise.
Substitution and integration by parts
The fundamental theorem turns every differentiation rule into an integration rule. The two used constantly, grouped as integration techniques, follow from the chain and product rules.
Proof
Since f is continuous on interval J, it has an antiderivative Φ(x)=∫x0xf on J by part 1 of the fundamental theorem. By the chain rule, (Φ∘φ)′=f(φ)φ′, which is continuous. Apply part 2 to both sides: both equal Φ(φ(β))−Φ(φ(α)).
∎
φ need not be injective or monotone: if φ goes out and back, segments traversed twice cancel with sign. This is specific to one variable and oriented integrals. In several variables, the change-of-variables formula integrates over unoriented sets, requires a bijection and uses ∣det∣ of the Jacobian instead of φ′.
Proof
(uv)′=u′v+uv′ is continuous, so by part 2, ∫ab(u′v+uv′)=u(b)v(b)−u(a)v(a). Separate the integral of the sum.
∎
Term [uv]ab is the boundary term. On a bounded interval it is calculated and that is it. On an unbounded interval or with an integrand singular at an endpoint, integrate on [ε,R] and take limits: the formula still holds if two of the three limits (left side, boundary term and right integral) exist, because then the third does too. Many useful identities reduce to the boundary term vanishing, which must be justified each time.
Improper integrals
The Riemann integral requires a bounded interval and bounded function. Expectations, normalizations and function Γ break both conditions. The solution is to integrate where possible and take a limit.
The last condition matters: limR→∞∫−RRf, the Cauchy principal value, can exist even when the integral diverges. We will see this with the Cauchy distribution.
Proof
For p=1, ∫1Rx−pdx=(R1−p−1)/(1−p), tending to 1/(p−1) if p>1 and to ∞ if p<1. For p=1, ∫1Rx−1dx=lnR→∞. At the origin, ∫ε1x−pdx=(1−ε1−p)/(1−p) for p=1 and ln(1/ε) for p=1, and the reasoning is the same.
∎
The thresholds are the same, p=1, but in opposite directions: the tail needs the function to fall quickly (large exponent) and the origin needs it not to blow up quickly (small exponent). Hence no power is integrable on all of (0,∞). With x↦1/x the two questions switch: ∫ε1x−pdx=∫11/εyp−2dy.
InteractiveDoes the tail converge?
Integrand x−p and both areas
Accumulated area as R and 1/ε increase
tail ∫₁ᴿ
origin ∫ε¹
tail limit
area at the origin, [ε,1]
tail area, [1,R]
Mode
∫1Rx−pdx1.368
∫ε1x−pdx4.325
Limits: tail, origin2.000, ∞
p>1: the tail converges to 1/(p−1)=2.000 and the origin diverges. No p makes ∫0∞x−pdx finite.
In ‘Powers’, orange area is ∫ε1x−p and aqua is ∫1Rx−p; on the right, both versus R and 1/ε, with dashed limits when they exist. Move p on either side of 1 and move R and ε away: on each side at most one curve stabilizes. Enable ‘View in u=lnx’: the integrand becomes e(1−p)u and at p=1 is constant 1, whose area grows without bound in both directions. In ‘Moments’, Student's t with ν degrees of freedom has ∣x∣kp(x)∼Cx−(ν+1−k): move ν to k or below and the truncated integral stops stabilizing. With ν=1 and k=1 (Cauchy) it grows like (2/π)lnR.
An antiderivative can almost never be calculated. Instead, compare with powers or exponentials.
Proof
(1) Φ(R)=∫aRf is increasing, because f≥0, and bounded by ∫a∞g. A bounded increasing function has a limit (limits of monotone functions, which is real completeness). (2) For large x, 2ℓg≤f≤2ℓg; apply (1) both ways from that point. (3) By the Cauchy criterion for limits, ∫aRh converges if and only if ∫RSh→0 as R,S→∞, and ∫RSh≤∫RS∣h∣, which tends to 0 because ∫∣h∣ converges (Cauchy sequences).
∎
The most used comparison tool is that the exponential beats any power: for every a∈R, xae−x/2→0 as x→∞, so xae−x≤Cae−x/2 for x≥1 and ∫1∞xae−xdx converges for everya. Similarly, ∫1∞xae−x2dx converges for every a. Near the origin, however, e−x→1 and the power dominates. In Landau notation, only the integrand’s order of magnitude matters at each problematic endpoint: f(x)∼Cx−q at infinity converges if and only if q>1.
Conditional convergence: sin(x)/x
The distinction is not a technicality. The Lebesgue integral admits only absolutely integrable integrands, so sin(x)/x is not Lebesgue integrable on [0,∞) even though its improper Riemann integral exists. And an expectation is defined as E[X]=∫xdF only when E∣X∣<∞, that is, when the integral converges absolutely (expectation). With merely conditional convergence, rearranging pieces or taking integration limits to infinity differently can change the result.
Bounded variation and the Riemann–Stieltjes integral
Integral ∫f(x)dx weights each piece of the axis by its length Δxi. To write the expectation of any discrete, continuous or mixed variable as one integral, weight by the probability F assigns to each piece, F(xi)−F(xi−1). Replacing Δxi by Δgi=g(xi)−g(xi−1) for a general integratorg works whenever g does not oscillate too much.
By the triangle inequality, V(g,P) does not decrease on refining P, so total variation is the limit of variations of increasingly fine partitions: the length of the graph’s vertical travel.
Monotone:Vab(g)=∣g(b)−g(a)∣, because the sum telescopes. Every distribution function has total variation 1 on R.
Lipschitz: if ∣g(x)−g(y)∣≤K∣x−y∣, Vab(g)≤K(b−a).
C1:Vab(g)=∫ab∣g′∣. By the mean value theorem, V(g,P)=∑i∣g′(ti)∣Δxi is a Riemann sum of ∣g′∣.
Continuous without bounded variation:g(x)=xcos(π/(2x)), with g(0)=0, is continuous on [0,1]. At points 1/(2k) it equals ±1/(2k) and at 1/(2k+1) it equals 0. The partition formed by 0, 1 and points 1/j with 2≤j≤2K+1 has V(g,P)≥∑k=1K1/(2k), unbounded in K by divergence of the harmonic series.
Proof
If g=g+−g− with both increasing, V(g,P)≤V(g+,P)+V(g−,P)=(g+(b)−g+(a))+(g−(b)−g−(a)). Conversely, let v(x)=Vax(g). Variation is additive, Vay=Vax+Vxy for x<y (partitions of [a,y] containing x are pairs of partitions of [a,x] and [x,y], and adding x does not decrease variation). Define g+=21(v+g) and g−=21(v−g), whose sum is v and difference g. For x<y, v(y)−v(x)=Vxy(g)≥∣g(y)−g(x)∣, so g+(y)−g+(x)=21(Vxy(g)+g(y)−g(x))≥0, and similarly for g−.
∎
Consequently everything known about monotone functions carries over to bounded-variation functions: they have one-sided limits everywhere, at most countably many discontinuities, all jumps, and are Riemann integrable.
Proof
(1) By Jordan decomposition and linearity of sums in g, it suffices to treat increasing g. By uniform continuity, for ε>0 there is δ such that ∣f(s)−f(t)∣<ε if ∣s−t∣<δ. If ∥P∥,∥Q∥<δ, compare both with common refinement R: each term f(ti)Δgi of P is split among the subintervals of R it contains, with tags less than δ apart, so ∣SP−SR∣≤ε∑iΔgi=ε(g(b)−g(a)), and similarly for Q. The sums satisfy the Cauchy condition as ∥P∥→0 and converge. The bound follows from ∣S∣≤sup∣f∣∑i∣Δgi∣≤sup∣f∣Vab(g).
(2) By the mean value theorem, Δgi=g′(si)Δxi with si∈(xi−1,xi), so S(f,g,P,t)=∑if(ti)g′(si)Δxi, differing from Riemann sum ∑if(ti)g′(ti)Δxi of fg′ by at most sup∣f∣⋅ω(∥P∥)(b−a), where ω is the modulus of uniform continuity of g′. The two have the same limit.
(3) If ∥P∥ is less than the minimum distance between jumps, each jump lies in one subinterval (or at the shared endpoint of two and is split between them), Δgi is zero on subintervals without jumps and the sum is ∑kf(ti(k))Jk plus terms sharing one jump, with tags less than ∥P∥ from ck. By continuity of f at ck, it converges to ∑kf(ck)Jk.
∎
If X takes values in (a,b] and its distribution function is the sum of a step part, with atoms at ck, and a class-C1 part with derivative p (the density), the theorem says that for continuous f,
E[f(X)]=∫abfdF=aˊtomosk∑f(ck)P(X=ck)+parte con densidad∫abf(x)p(x)dx,
one formula covers discrete, continuous and mixed cases. Equality E[f(X)]=∫fdF holds for any F, including those with neither atoms nor a density (such as the Cantor function); only the right-hand formula requires the decomposition. For unbounded variables take improper limit ∫−∞∞fdF=lim∫−RSfdF, under the same absolute-convergence condition as before.
InteractiveRiemann–Stieltjes sums and expectations
Integrand f and values at tags ti
Integrator g and polygonal line of increments Δgi
Contributions f(ti)Δgi from each subinterval (their sum is S)
integrand f
integrator g (distribution function)
tags, increments and contributions
Tag ti
S=∑if(ti)Δgi1.9800
E[X]=∫fdF1.9500
Error ∣S−∫fdg∣0.0300
Variation ∑i∣Δgi∣1.0000
Atoms and density together: the sum converges to 0.2f(1)+0.3f(2.5)+∫f(x)81dx. Neither a sum nor a Riemann integral expresses both alone.
Integrator g is a distribution function on [0,4]; the sum weights the value of f at each tag by increment Δgi, made visible by the magenta polygonal line. With the mixed distribution, two subintervals containing atoms get tall bars and the rest thin bars: increase n and watch S approach E[f(X)]. Switch to discrete and continuous: the same formula becomes a sum and an integral with density. Then choose f=1[x>2.5], which jumps where g has an atom, and alternate left and right tags with odd n. Finally, the integrator without bounded variation: does ∑i∣Δgi∣ stabilize?
What the figure shows for a shared jump is a theorem: if f and g are discontinuous at the same point, ∫fdg does not exist. If the point lies inside a subinterval, the tag decides whether to count the jump of g with the value of f on one side or the other, and the difference does not shrink under refinement. When it exists, the integral satisfies an integration by parts formula without differentiability assumptions: ∫abfdg+∫abgdf=f(b)g(b)−f(a)g(a).
The Gamma function
The most frequent combination of power and exponential deserves its own name.
The integral converges exactly when x>0. At infinity, the exponential beats power tx−1 for every x. At the origin, e−t→1 and the integrand behaves like tx−1=t−(1−x), integrable on (0,1] if and only if 1−x<1, that is, x>0.
Proof
(1) ∫0∞e−tdt=limR(1−e−R)=1. (2) This is integration by parts with two boundary terms to control; you will do it in the guided exercise. (3) By induction using (1) and (2): Γ(n+1)=nΓ(n)=n(n−1)!=n!. (4) In [ε,R], substitute t=u2, dt=2udu:
using the Gaussian integral∫−∞∞e−u2du=π, calculated in polar coordinates in the multiple-integrals lesson. Since the integrand is even, half is π/2.
∎
Thus Γ is factorial extended to positive reals: Γ(3/2)=21π, Γ(5/2)=43π and, generally, Γ(n+21)=4nn!(2n)!π. It is not the only function interpolating n!, but is the unique one that is also log-convex on (0,∞) and satisfies Γ(1)=1 and the recurrence (Bohr–Mollerup theorem). Reading the recurrence backward, Γ(x)=Γ(x+1)/x, extends it to noninteger negatives, with poles at 0,−1,−2,…
What you should learn to recognize is the general form. With t=bx,
∫0∞xae−bxdx=ba+1Γ(a+1)(a>−1,b>0).
This yields the normalization constant of the Gamma family, ∫0∞xα−1e−βxdx=Γ(α)/βα; exponential moments, E[Xk]=k!/λk; and, with u=x2/2, absolute normal moments, E∣Z∣k=2k/2Γ(2k+1)/π, which the tail figure uses as a reference. Later, Γ will give the volume of the ball in n dimensions, and its growth is described by Stirling’s formula, Γ(x+1)∼2πx(x/e)x, obtained by Laplace’s method applied to this same integral.
Implementation from scratch
The first cell implements Darboux sums for piecewise monotone functions: if f is monotone on each piece, its extrema on each subinterval are at the edges, so L and U are computed exactly up to rounding, with n+1 evaluations per piece. The result is an interval certain to contain the integral, unlike the midpoint rule, which is often more accurate but does not say by how much it is wrong.
[ ]Darboux sums with a certificateBrowser
import numpy as np
def darboux_monotone(f, a, b, n, breaks=()):
"""Sumas inferior y superior de f en [a, b] con n subintervalos iguales por tramo.
f debe ser monótona en cada tramo [c_j, c_{j+1}] que definen los puntos de ruptura:
entonces su ínfimo y su supremo en cada subintervalo están en los extremos."""
cortes = np.array([a, *sorted(breaks), b], dtype=float)
L = U = 0.0
for c0, c1 in zip(cortes[:-1], cortes[1:]):
x = np.linspace(c0, c1, n + 1)
y = f(x)
izq, der = y[:-1], y[1:]
dx = (c1 - c0) / n
L += dx * np.minimum(izq, der).sum()
U += dx * np.maximum(izq, der).sum()
return L, U
def punto_medio(f, a, b, n):
x = a + (np.arange(n) + 0.5) * (b - a) / n
return (b - a) / n * f(x).sum()
f = lambda x: np.exp(-x**2)
exacto = 0.7468241328124270 # ∫_0^1 e^{-x^2} dx = (√π/2) erf(1)
print(f"{'n':>6} {'L':>12} {'U':>12} {'U - L':>10} {'error p. medio':>15}")
for n in [4, 16, 64, 256, 1024]:
L, U = darboux_monotone(f, 0.0, 1.0, n)
assert L <= exacto <= U
print(f"{n:6d} {L:12.8f} {U:12.8f} {U - L:10.2e} {abs(punto_medio(f, 0, 1, n) - exacto):15.2e}")
# monótona a trozos: sen x en [0, π] crece hasta π/2 y luego decrece
L, U = darboux_monotone(np.sin, 0.0, np.pi, 100, breaks=[np.pi / 2])
print(f"\n∫_0^π sen x: {L:.6f} ≤ 2 ≤ {U:.6f} (U - L = {U - L:.2e})")
# una monótona con saltos: la parte entera en [0, 3.5]
L, U = darboux_monotone(np.floor, 0.0, 3.5, 1000)
print(f"∫_0^3.5 ⌊x⌋: {L:.6f} ≤ 4.5 ≤ {U:.6f}")
Column U - L is exactly (1−e−1)/n: it divides by 4 each time n is multiplied by 4. Midpoint error divides by 16 because it is order 1/n2 for C2 functions (errors in the two halves of each subinterval cancel to first order), but that bound requires knowing f′′. Certification and acceleration combine in adaptive quadrature and Gaussian quadrature.
The second cell checks the fundamental theorem: accumulate F(x)=∫0xf with the midpoint rule on a fine grid, differentiate with central differences and compare with f. At a jump the numerical derivative gives no warning: it returns the average of the one-sided slopes, a number that is not the derivative of anything.
[ ]The fundamental theorem, numericallyBrowser
import numpy as np
import matplotlib.pyplot as plt
def acumulada(f, a, b, m):
"""F(x_j) = ∫_a^{x_j} f en una malla uniforme de m subintervalos (regla del punto medio)."""
x = np.linspace(a, b, m + 1)
medios = (x[:-1] + x[1:]) / 2
F = np.concatenate([[0.0], np.cumsum(f(medios)) * (b - a) / m])
return x, F
f = lambda x: 1.5 * np.cos(0.9 * x) + 0.3
x, F = acumulada(f, 0.0, 4.0, 4000)
dF = np.gradient(F, x) # diferencias centradas en el interior
print("máx |F' - f| con f continua:", f"{np.abs(dF[1:-1] - f(x[1:-1])).max():.1e}")
# con un salto en x = 2, la derivada numérica de F en el salto es el promedio de las laterales
g = lambda x: np.where(x < 2, 0.4 * x + 0.2, 0.4 * x - 1.4)
x, G = acumulada(g, 0.0, 4.0, 4000)
dG = np.gradient(G, x)
i = np.searchsorted(x, 2.0)
print(f"pendiente de G: a la izquierda {dG[i-3]:.4f}, en 2 {dG[i]:.4f}, a la derecha {dG[i+3]:.4f}")
# decaimiento: cota de Darboux U - L frente al error real del punto medio, para e^x en [0, 1]
ns = 2 ** np.arange(2, 15)
cota = [darboux_monotone(np.exp, 0, 1, n)[1] - darboux_monotone(np.exp, 0, 1, n)[0] for n in ns]
err_pm = [abs(punto_medio(np.exp, 0, 1, n) - (np.e - 1)) for n in ns]
p1 = np.polyfit(np.log(ns), np.log(cota), 1)[0]
p2 = np.polyfit(np.log(ns), np.log(err_pm), 1)[0]
print(f"pendientes log-log: cota U - L {p1:.3f}, error del punto medio {p2:.3f}")
plt.loglog(ns, cota, "o-", label="U − L (garantizado)")
plt.loglog(ns, err_pm, "s-", label="error del punto medio")
plt.xlabel("n"); plt.ylabel("error"); plt.legend(); plt.show()
Error of F′ against f is of order 10−7 with f continuous, combining quadrature error with central-difference error, both order h2. At the jump, the “slope” is 0.2, the average of 1 and −0.6. Graph slopes −1 and −2 match theory. Systematic numerical integration (Simpson, Gauss, adaptive methods and error analysis) belongs to numerical methods.
With libraries: SciPy and SymPy
scipy.integrate.quad wraps QUADPACK, an adaptive Gauss–Kronrod quadrature library. It accepts infinite bounds (internally changing variables to map [a,∞) to a bounded interval), returns the value and an absolute-error estimate, and has special routines for oscillatory integrands. scipy.special.gamma evaluates Γ directly.
[ ]Gamma and improper integrals with SciPyBrowser
import warnings
import numpy as np
from scipy import integrate, special
# Γ(x) por cuadratura frente a special.gamma
for x in [0.5, 1.0, 2.5, 5.0, 7.3]:
val, err = integrate.quad(lambda t: t**(x - 1) * np.exp(-t), 0, np.inf)
print(f"x = {x}: quad = {val:.12f} gamma = {special.gamma(x):.12f} error estimado {err:.0e}")
print("Γ(n + 1) = n! para n = 0..7:", all(special.gamma(n + 1) == special.factorial(n) for n in range(8)))
print("Γ(1/2)² - π =", special.gamma(0.5) ** 2 - np.pi)
# ∫ x^p e^{-x} en [0, ∞) converge si y solo si p > -1; cerca de -1 el valor explota como 1/(p + 1)
for p in [-0.5, -0.9, -0.99]:
val, _ = integrate.quad(lambda t: t**p * np.exp(-t), 0, np.inf)
print(f"p = {p}: quad = {val:.6f} Γ(p + 1) = {special.gamma(p + 1):.6f}")
# sen(x)/x en [0, ∞): [0, 1] normal y [1, ∞) con la rutina de Fourier (QAWF)
I1, _ = integrate.quad(lambda x: np.sinc(x / np.pi), 0, 1) # np.sinc(t) = sen(πt)/(πt)
I2, _ = integrate.quad(lambda x: 1 / x, 1, np.inf, weight="sin", wvar=1)
print(f"\n∫_0^∞ sen(x)/x = {I1 + I2:.12f} π/2 = {np.pi / 2:.12f}")
with warnings.catch_warnings(record=True) as avisos:
warnings.simplefilter("always")
ingenuo, err = integrate.quad(lambda x: np.sinc(x / np.pi), 0, 1000)
print(f"quad sin ayuda en [0, 1000]: {ingenuo:.6f}, error estimado {err:.0e}, avisos: {len(avisos)}")
# |sen x|/x: la integral hasta Kπ crece como (2/π) ln(Kπ) más una constante
arcos = [integrate.quad(lambda x: np.abs(np.sinc(x / np.pi)), k * np.pi, (k + 1) * np.pi)[0] for k in range(2000)]
acum = np.cumsum(arcos)
for K in [10, 100, 1000, 2000]:
R = K * np.pi
print(f"R = {K:4d}π: ∫_0^R |sen x|/x = {acum[K - 1]:.4f} diferencia con (2/π) ln R = {acum[K - 1] - 2 / np.pi * np.log(R):.4f}")
Three readouts. quad reproduces Γ to 11 or 12 digits and its error estimate is honest. With the Fourier routine, ∫0∞sin(x)/x has about 10 digits; unaided, at [0,1000], quad exhausts its subdivisions and warns, with error estimate 0.2. And the integral of ∣sinx∣/x up to Kπ minus (2/π)ln(Kπ) stabilizes around 1.11: it grows logarithmically, exactly the harmonic series’ slow divergence.
SymPy calculates exact antiderivatives and values. But not every elementary function has an elementary antiderivative: a theorem of Liouville (1835) characterizes when one exists, and e−x2, sin(x)/x or e−x3 do not have one. SymPy then returns special functions defined precisely as those integrals: erf, Si or the incomplete Gamma.
The antiderivative of e−x2 is 2πerf(x), and that of sin(x)/x is the sine integral function Si(x). The value at [0,∞) being π/2 is due to no antiderivative but to a two-dimensional trick (polar coordinates). Symbolic calculations are excellent references to check closed-form answers; for integrals with data, numerical parameters or high dimension, quadrature or Monte Carlo is used.
Common mistakes
Exercises
ProofThe derivative of accumulation
Prove: If f is continuous on [a,b] and F(x)=∫axf(t)dt, then F is differentiable at every x∈[a,b] (one-sided at endpoints) and F′(x)=f(x).
0
Fix x∈[a,b) and take h>0 with x+h≤b. Case h<0 is analogous.
Step 1 of 4. How do you write increment F(x+h)−F(x)?
NumericAn apparent singularity
Calculate ∫01xlnxdx.
ProofThe Gamma recurrence
Prove: For every x>0, Γ(x+1)=xΓ(x).
0
Work on [ε,R] with 0<ε<R and take limits ε→0+ and R→∞ at the end.
Step 1 of 5. How do you choose the parts in ∫εRtxe−tdt?
QuizPower times exponential
For which values of p∈R does ∫0∞xpe−xdx converge?
QuizA negative integral of something positive
Applying the fundamental theorem, ∫−11x−2dx=[−x−1]−11=−1−1=−2, a negative number for a positive integrand. Where is the mistake?
QuizWhich are Riemann integrable on [0, 1]?
Choose all functions Riemann integrable on [0,1] (for those undefined at 0, take f(0)=0).
More than one answer may be correct.
NumericHow many subintervals guarantee six digits?
For f(x)=e−x2 on [0,1], which is decreasing, estimate using midpoint (L+U)/2 of the Darboux sums with n equal subintervals. What is the smallest n that guarantees error at most 10−6?
NumericA noninteger factorial
Calculate Γ(5/2).
NumericRecognizing a Gamma
Calculate ∫0∞x3e−2xdx.
NumericA mixed Riemann–Stieltjes integral
Let g(x)=x+⌊x⌋ on [0,2]. Calculate ∫02x2dg(x).
CodeIntegration with a guarantee
Implement darboux(f, a, b, n) for fmonotone (increasing or decreasing) on [a,b], returning the tuple (inferior, superior) of Darboux sums with n equal subintervals; f accepts NumPy arrays. Also implement integrate_to_tol(f, a, b, tol), trying n = 1, 2, 4, 8, ... and returning (valor, n) with the firstn for which (superior - inferior) / 2 <= tol, where valor = (inferior + superior) / 2. The distance from valor to the exact integral is thus guaranteed below tol.
import numpy as np
def darboux(f, a, b, n):
"""Devuelve (inferior, superior) para f monótona en [a, b] con n subintervalos iguales."""
# tu código
return 0.0, 0.0
def integrate_to_tol(f, a, b, tol):
"""Duplica n desde 1 hasta que (U - L)/2 <= tol; devuelve ((L + U)/2, n)."""
# tu código
return 0.0, 1
Shift+Enter to run
Summary
Key idea
The Riemann integral exists when area is trapped between two staircases that close under refinement; the fundamental theorem converts it into an increment of antiderivatives, and everything else (improper integrals, Stieltjes, Gamma) consists of controlled limits of the same idea.
Darboux sums L≤∫f≤U move closer under refinement. f is integrable if and only if U−L can be made smaller than any ε, and then Riemann sums converge as mesh shrinks, with any tags.
Monotone functions (with U−L≤∣f(b)−f(a)∣∥P∥, a certificate) and continuous functions are integrable. Generally, a bounded function is integrable if and only if its discontinuities have measure zero: Thomae yes, Dirichlet no.
Fundamental theorem: F(x)=∫axf is Lipschitz and F′=f at each continuity point; if G′=f throughout the interior and f is integrable, ∫abf=G(b)−G(a). A jump in f gives a corner in F.
Substitution and parts are the chain and product rules integrated. On unbounded domains, the boundary term must be proved to vanish.
Improper integrals are decided by comparison with x−p (threshold p=1, in opposite directions at 0 and ∞) and exponentials. Absolute convergence matters for expectations: Cauchy has no mean, and Student’s t has moments of order k if and only if ν>k.
The Riemann–Stieltjes integral ∫fdg, with f continuous and g of bounded variation (difference of increasing functions), unifies sums and integrals: E[f(X)]=∫fdF for continuous f and any discrete, continuous or mixed variable.
Γ(x)=∫0∞tx−1e−tdt converges for x>0, satisfies Γ(x+1)=xΓ(x), Γ(n+1)=n! and Γ(1/2)=π, and underlies every integral of the form ∫0∞xae−bxdx=Γ(a+1)/ba+1.