Integration
local graph
When we first encountered the concept of derivatives in Chapter 12, we introduced it through an example from physics. As Newton created it, the derivative describes the velocity of a moving object as calculated from its time-distance graph. In other words, the velocity can be derived from the time-distance information.
Can the distance be reconstructed given the velocity? In a sense, this is the inverse of differentiation.
Questions such as these are hard to answer if we only look at the most general case, so let’s consider a special one. Suppose that our object is moving with a constant velocity v(t) = v0
, for a duration of T seconds. With some elementary logic, we can conclude that the total distance traveled is v0T meters.
When taking a look at the time-velocity plot, we can immediately see that the distance is the area under the time-velocity function graph v(t) = v0.
The graph of v(t) describes a rectangle with width v0 and length T, hence its area is indeed v0T.

Figure 14.1: Time-velocity plot of an object, moving with constant velocity
Does the area under v(t) equal the distance traveled in the general case? For instance, what happens when the time-velocity plot looks something like this?

Figure 14.2: Time-velocity plot of an object, moving with a changing velocity
The speed is not constant here. In this case, we can do a simple trick: partition the time interval [0,T] into smaller ones and approximate the object’s motion as a constant-speed motion on each of these intervals.

Figure 14.3: Approximating with a constant velocity motion
If the time intervals [ti,ti+1] are sufficiently granular, the distance traveled will roughly match a constant velocity motion with the average velocity at [ti,ti+1]. That is, if we introduce the notation
![vi := average velocity during the time interval [ti−1,ti], i = 1,2,...,n,](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1316.png)
we should have
![∑n vi(ti − ti−1) ≈ total distance traveled during [0,T]. i=1](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1317.png)
Let’s think about this whole process as approximating the function v(t) with a stepwise constant function vapprox(t). From this angle, we have

and

(Very) loosely speaking, if the granularity of the time intervals [ti,ti+1] gets infinitesimally small, the approximations turn into equality. Thus,
![total distance traveled during [0,T ] = area under v(t) in [0,T ].](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1320.png)
There are two key points that we need to remember: if s(t) is the distance traveled and v(t) is the velocity, then
- v(t) is the derivative s′(t),
- and s(T) is the area under the graph v(t) between 0 and T.
In other words, calculating the area under the curve is the same as inverting differentiation. This process is called integration.
Unfortunately, things are not as simple as they seem. We missed a lot of mathematical detail in the above discussion. For one, does the sum

converge if the partition of [0,T] gets more granular? Does the limit depend on the partitions? Can we even define the area under the “graph” for all functions? Like the Dirichlet function, defined by
.png)
(14.1)
How do we calculate limits of ∑ i=1nvi(ti −ti−1) in practice? In addition, what does all of this have to do with machine learning?
Fasten your seatbelts! Here comes the rigorous study of integration, clearing up all of these questions.
Bookmark
14.1 Integration in theory
Section titled “14.1 Integration in theory”Let’s build a solid theoretical foundation for the intuitive explanation! Let f : [a,b] →ℝ be an arbitrary bounded function, and our goal is to calculate the signed area under the graph. (Note that the signed area is negative if the graph goes below the x axis. In the time-speed graph example above, this is equivalent to moving backward, thus decreasing the distance traveled from the starting point.)
Let a = x0>x1>…>xn = b an arbitrary partition of the interval [a,b].
For notational convenience, we’ll denote this partition as X = {x0,…,xn} as well. The granularity (or mesh) of X is defined by

which is the length of the biggest gap in X. Note that the partition is not necessarily uniform, so jxi −xi−1j is not constant.
We are going to use an argument similar to the squeeze principle (Corollary 3) to make the approximation idea rigorous. (You know, the one where we replaced the speed of a moving object with a piecewise constant one.) Instead of using the averages of f(x) on each interval [xi−1,xi], we are going to provide an upper and lower estimation by using
![mi := inf f (x ) x∈[xi−1,xi]](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1324.png)
and
![Mi := sup f(x). x∈ [xi− 1,xi]](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1325.png)
Mathematically speaking, the infimum and the supremum are much easier to work with than the average. Now we can approximate f(x) with a piecewise constant function from both above and below. This is visualized by Figure 14.4.

Figure 14.4: Estimating the area under the curve of f using the partition X
Our plan is to squeeze the area between the lower and upper sums
L[f, X] := ∑i=1n mi(xi − xi−1) (14.2)
and
U[f, X] := ∑i=1n Mi(xi − xi−1), (14.3)
then study if these two match. (As usual, the dependence on f and X will be omitted if it is clear from the context.)
It is clear from the construction that
![L[f,X ] ≤ area under the graph ≤ U [f,X ]](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1327.png)
holds for any partition X.
As the granularity of the partition X goes to zero, hopefully, both L[f,X] and U[f,X] will converge to the same number. Intuitively, this common limit should be the “area under the function graph,” but currently, our notion of the area is not general enough to make such bold statements. For instance, how would you define the “area” under the Dirichlet function, defined by (14.1)? As we shall see soon, integration will generalize our heuristic notion of area. To get to that point, we have a lot to do. First, we’ll take a closer look at the partitions.
14.1.1 Partitions and their refinements
Section titled “14.1.1 Partitions and their refinements”We need to introduce some basic facts about refining partitions to construct mathematically correct arguments regarding the convergence of the approximating sums L[f,X] and U[f,X].
Definition 63. (Refinement of partitions)
Let X = {x0,…,xn} and Y = {y0,…,ym} be two partitions of [a,b]. We say that Y is a refinement of X if X ⊆Y .
We can visualize this easily.

Figure 14.5: The partition Y , as a refinement of X
Refinements are vital for understanding why integration works. One of the core reasons is the following result.
Definition 64. Monotonicity of upper and lower sums
Let f : [a,b] →ℝ be a bounded function and X and Y be two partitions of [a,b]. Suppose that Y is a refinement of X. Then
L[f, X] ≤ L[f, Y] (14.4)
and
U[f, Y] ≤ U[f, X]. (14.5)
Proof. We are going to show L[f,X] ≤ L[f,Y ], as (14.5) follows from a similar argument. Suppose that xi−1 ≤ yj ≤ ⋅⋅⋅ ≤ yl ≤ xi. Mathematically speaking, we have
![inf f(x) ≤ inf f(x), k = j + 1,...,l. x∈[xi−1,xi] x∈[yk−1,yk]](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1330.png)
Since xi −xi−1 = ∑ k=j+1lyk −yk−1, the above implies that

(14.6)
Don’t worry if these mathematical formalisms make this hard to follow. Just take a look at Figure 14.6 below, which summarizes all that we have done so far.

Figure 14.6: Refinement of lower sums
Since L[f,X] and L[f,Y ] are composed from parts like in (14.6), summing over i in the above immediately yields L[f,X] ≤L[f,Y ].
We are almost there. There is one thing left for us to show: that for any two partitions, the lower sum is always smaller than the upper sum. Hence, the squeeze principle (Corollary 3) could be applied to show that the lower and upper sums converge to the same limit in some instances.
For that, we need a simple but fundamental fact about partitions.
Proposition 3.
Let
and
be two partitions of
. Then there exists a partition
that is a refinement of both
and
.
Proof. It is easy to see that
satisfies our requirements.
The above Z is called a mutual refinement of X and Y . We can show a fundamental relation between the upper and lower sums with this idea.
Proposition 4.
Let f : [a,b] → ℝ be a bounded real function and let X and Y be two partitions of the interval [a,b]. Then
![L [f,X ] ≤ U[f,Y ]](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1340.png)
holds.
Proof. Let Z be a mutual refinement of X and Y , as guaranteed by the previous result. Then, (14.4) and (14.5) imply that
![L[f,X ] ≤ L [f,Z ] ≤ U [f,Z ] ≤ U [f,Y],](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1341.png)
which is what we wanted to show.
14.1.2 The Riemann integral
Section titled “14.1.2 The Riemann integral”Let’s denote the set of all partitions on [a,b] by ℱ[a,b]:
![ℱ [a,b] = {X : X is a partition of [a,b]}.](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1342.png)
Now we are ready to define the integral of the function as the single value that separates upper and lower sums.
Definition 65. (Riemann-integrability)
Let f : [a,b] → ℝ be a bounded function. We say that f is Riemann-integrable (or just integrable) on [a,b] if
![X∈suℱp[a,b]L[f,X ] = X i∈nℱf[a,b]U [f,X ].](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1343.png)
This value is called the Riemann integral (or just the integral) of f over [a,b], denoted by

The function f in ∫ abf(x)dx is called the integrand. How do we calculate the integral itself? The hard way is to define a sequence of partitions Xn and show that
![lim L[f,Xn ] = lim U[f,Xn ], n→ ∞ n→ ∞](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1345.png)
so this number is necessarily ∫ abf(x)dx. We’ll see the easy way soon, but let’s see an example demonstrating this process.
Let’s calculate ∫ 01x2dx!
The simplest is to use the uniform partition Xn = i∕ni=0n, obtaining
![∑n i − 1 21 L[x2,Xn ] = (-----) -- i=1 n n 1 ∑n = -3- (i− 1)2. n i=1](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1346.png)
Since ∑ k=1nk2 =
(as it can be shown by induction), it is easy to see that
![2 1 nli→m∞ L[x ,Xn ] = 3.](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1348.png)
With a similar argument, you can check that limn→∞U[x2,Xn] =$$
as well, thus, ∫ 01x2dx exists and

Although this method works for simple cases such as f(x) = x2, it breaks down for more complex functions, as calculating limits of upper and lower sums can be difficult. In addition, selecting the right partition is also a challenge. For instance, can you calculate ∫ 0π sin(x)dx by the definition?
Because we are lazy (just like any good mathematician), we want to find a general method to calculate integrals. Lower and upper sums are needed to make the notion of an integral mathematically precise. Combined with the squeeze principle (Corollary 3), they are used to provide a definition.
However, other tools become available once we know that a function is integrable. Such as the general approximating sum, as we are about to see next.
Theorem 91. Let
be an arbitrary bounded function, and let
be a sequence of partitions on
such that
. Then
is integrable if and only if the limit

exists and in this case,

holds, where ξi ∈ [xi−1,n,xi,n].
(Note that jXnj → 0 means that the length of the largest subinterval of Xn gets extremely small. In other words, the resolution of Xn gets extremely large.)
We will not prove the above theorem, as the proof is technical and doesn’t provide any valuable insight. However, the point is clear: local infima and suprema in lower and upper sums can be replaced with any local value.
For simplicity, we’ll denote this sum by
S[f, X, \xi_X] = \sum_{i=1}^n f(\xi_i)(x_i - x_{i-1}) (14.7)
for any X = {x0,…,xn} and ξX = {ξ1,…,ξn} with ξi ∈ [xi−1,xi].
14.1.3 Integration as the inverse of differentiation
Section titled “14.1.3 Integration as the inverse of differentiation”Now that we understand the mathematical definition of the integral, it is time to find some tools that enable its use in practice. The most important result is the Newton-Leibniz formula, named after Isaac Newton and Gottfried Wilhelm Leibniz, the inventors of calculus. (Fun fact: these men discovered calculus independently and were mortal enemies throughout their lives.)
Theorem 92. (The fundamental theorem of calculus, a.k.a. the Newton-Leibniz formula)
Let f : ℝ →ℝ a function that is integrable on [a,b] and suppose that there is an F : ℝ →ℝ such that F′(x) = f(x). Then
∫ₐᵇ f(x) dx = F(b) − F(a) (14.8)
holds.
In other words, by defining x→F(a) + ∫ axf(x)dx, we can effectively reconstruct a function from its derivative.
Proof. Let
be an arbitrary partition of
. According to Lagrange’s mean value theorem (Theorem 89), there exists a
for all
such that

Thus, we can sum these numbers up, eliminating all but the first and last elements:

On the other hand, due to the properties of lower and upper sums, we have
![∑n L[f,X ] ≤ f(ξ)(x − x ) ≤ U[f,X ] i=1 i i i−1](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1365.png)
Since f is integrable, the squeeze principle (Corollary 3) and Theorem 91 imply that

must hold. This is what we had to show.
Remark 10. (Increments of functions)
For simplicity, the increments of a function F on the interval [a,b] is also denoted by
![x=b [F(x)]x=a := F (b)− F (a ).](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1367.png)
Thus, according to the fundamental theorem of calculus (Theorem 92),
![∫ b f(x)dx = [F (x)]x=x=ba a](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1368.png)
holds if F′(x) = f(x).
Note that integration is insensitive towards changing the values of f(x) at countably many points. To be more precise, suppose that f : ℝ →ℝ is a function that is integrable on [ − 1,1]. Let’s change its value at a single point and define

If a partition is given by −1 = x0>…>xk−1 ≤ 0>xk>…>xn = 1, then
![|L[f,X] − L[f∗,X ]| = | inf f (x)− inf f∗(x)|(xk − xk− 1) x∈[xk−1,xk] x∈[xk−1,xk] ◟------------=◝:◜m--------------◞ k](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1370.png)
and
![∗ ∗ |U [f,X] − U[f ,X ]| = |x∈s[xukp−1,xk]f(x)− x∈[sxuk−p1,xk]f (x )|(xk − xk −1) ◟-------------◝◜--------------◞ =](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1371.png)
holds. We can select the partition such that
for some arbitrary
, thus,
![|L[f,X ]− L[f∗,X ]| and |U [f,X ]− U[f∗,X ]|](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1374.png)
can be made as small as needed. This implies that

Hence, saying that integration is the inverse of differentiation is mathematically a bit imprecise. Given a differentiable function F(x), its derivative is unique, but there are infinitely many functions whose integral F(a) + ∫ axg(y)dy reconstructs F.
The fundamental theorem of calculus allows us to formulate Lagrange’s mean value theorem (Theorem 89) in terms of integrals.
Theorem 93. (The mean value theorem for definite integrals)
Let f : ℝ →ℝ a function that is continuous on [a,b]. Then there exists an ξ ∈ [a,b] such that

Proof. According to the fundamental theorem of calculus (Theorem 92), the function

is differentiable on [a,b] and F′(t) = f(t).
Thus, Lagrange’s mean value theorem (Theorem 89) gives that

for some ξ ∈ (a,b), from which

follows. This is what we had to show.
After all this theory, you might ask: what does integration have to do with machine learning? Without being mathematically rigorous, here is a (very) brief overview of what’s to come.
First, you can think about integration as a continuous generalization of the arithmetic mean. As you can see, for equidistant partitions, an approximating sum
![∑n S[f,X,ξ] = 1- f(ξi) n i=1](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1380.png)
is exactly the average of f(ξ1),…,f(ξn). In machine learning, averages are frequently used to express various quantities, like the mean-squared error. Think about it: loss functions are often averages of certain individual losses. On a fine enough scale, averages become integrals.
Along with linear algebra and calculus, the central pillar of machine learning is probability theory and statistics, which gives us a way to model the world based on our observations. Probability and statistics are the logic of science and decision-making. There, integration is used to express probabilities, expected value, information, and much more. Without a rigorous theory of integration, we cannot build probabilistic models beyond a certain point.
Bookmark
14.2 Integration in practice
Section titled “14.2 Integration in practice”Even though we understand what an integral is, we are far from computing them in practice. As opposed to differentiation, analytically evaluating integrals can be really difficult and sometimes downright impossible. The formula (92) suggests that the key is to find the function whose derivative is the integrand, called the antiderivative or primitive function. This is harder than you think. Nevertheless, there are several tools for this, and we are going to devote this section to studying the most important ones.
Often, the key is finding the antiderivative, so we introduce the notation

for the functions where F′ = f. (Sometimes we abbreviate this to F = ∫ fdx.) Note that since (F + some constant)′ = F′, the antiderivative ∫ f(x)dx is not uniquely determined. However, this is not an issue for us, as the Newton-Leibniz formula states that

Thus, any additional constants would be eliminated.
With this under our belt, we are ready to dig deep into evaluating integrals in practice.
14.2.1 Integrals and operations
Section titled “14.2.1 Integrals and operations”As we have seen this several times (for instance, when discussing the rules of differentiation in Theorem 80), the relations of an operation with addition, multiplication, and possibly others are extremely useful for gaining insight and developing practical tools.
This is the same for integration as well. Similar to before, the linearity of the integral is our main tool to evaluate it.
Theorem 94. (Linearity of the Riemann integral)
Let f,g : ℝ →ℝ be two functions that are integrable on [a,b]. Then
(a) ∫ ab(f(x) + g(x))dx = ∫ abf(x)dx + ∫ abg(x)dx,
(b) ∫ abcf(x)dx = c∫ abf(x)dx.
Proof. (a) If f and g are integrable, then for any 𝜀 >0, there are partitions Xf,Xg such that
![∫ ∫ b b a f(x)dx− 𝜀 ≤ L [f,Xf ] ≤ U [f,Xf] ≤ a f(x)dx + 𝜀](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1385.png)
and
![∫ b ∫ b g(x)dx− 𝜀 ≤ L [g,Xg ] ≤ U [g,Xg ] ≤ g(x )dx + 𝜀, a a](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1386.png)
where the lower and upper sums are defined by (14.2) and (14.3). So, for the mutual refinement X = Xf ∪Xg, we have
![L[f,Xf ] ≤ L [f,X ], L [g,Xg ] ≤ L [g,X ], U[f,X ] ≤ U [f,Xf ], U[g,X ] ≤ U [g,X ] g](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1387.png)
due to the Proposition 4. Thus,
![∫ ∫ b b f(x)dx+ g(x)dx− 2𝜀 ≤ L [f,Xf ]+ L [g,Xg ] a a ≤ L [f,X ]+ L [g,X ] ≤ S [f,X, ξX]+ S[g,X,ξX ] ≤ U [f, X]+ U[g,X ] ≤ U [f, Xf]+ U [g,Xg] ∫ ∫ b b ≤ a f (x)dx+ a g(x )dx + 2𝜀,](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1388.png)
where S is defined by (14.7). From this definition, it can also be seen that
![S[f + g,X, ξX ] = S[f,X, ξX]+ S [g,X, ξX].](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1389.png)
Thus,

implying that

Theorem 91 regarding the approximating sum S implies that f + g is integrable on [a,b] and

(b) This follows from the fact that S[cf,X,ξX] = cS[f,X,ξX].
14.2.2 Integration by parts
Section titled “14.2.2 Integration by parts”As we have learned when studying the rules of differentiation (Theorem 80), for an arbitrary f and g, we have

Applying this logic to the antiderivatives,

holds. Rearranging the equation a bit, we obtain the formula of integration by parts:
∫ f′g dx = fg − ∫ fg′ dx. 14.9
This is summed up in the following theorem.
Theorem 95. (Integration by parts)
Let f,g : ℝ →ℝ be two functions. If both are differentiable on the interval [a,b], then
![∫ b ∫ b f′(x)g(x)dx = [f(x)g(x)]x=b − f(x)g′(x)dx a x=a a](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1395.png)
holds.
How is this useful for us? Consider a situation where finding the antiderivative of f and the derivative of g is easy, but the antiderivative of the product fg is hard. For example, can you quickly calculate the following?

Applying (14.9) with the roles f′(x) = x and g(x) = log x immediately yields

where C ∈ℝ is an arbitrary constant.
14.2.3 Integration by substitution
Section titled “14.2.3 Integration by substitution”As the integration by parts formula is the “opposite” of the differentiation rule for products, there is an analogue for the chain formula as well. Recall that for two differentiable functions, we had

Translating this to the language of integrals, we obtain the following result.
Theorem 96. (Integration by substitution)
Let f,g : ℝ → ℝ be integrable functions on [a,b]. Suppose that f is continuous and g is differentiable. Then

holds.
This is called integration by substitution. To give you an example of its use, consider

With the roles y(x) = x2, we have

where C ∈ℝ is an arbitrary constant.
Integration by parts and substitution are our main weapons for calculating integrals on paper. Most of the integrals one might encounter can be solved with the creative (and possibly iterated) application of these two rules. The recipe is simple: find the antiderivative, then use the Newton-Leibniz formula (Theorem 92) to compute the value of the integral.
However, there is a serious issue: antiderivatives can be extremely hard to find, maybe even impossible. This makes integrals difficult to compute symbolically. For instance, consider

where the function e−x2 describes the well-known Gaussian bell curve. As surprising as it is, ∫ e−x2 dx cannot be described with a closed formula! (That is, one that uses a finite number of operations and only elementary functions.) It’s not that mathematicians were not clever enough to find a closed formula for the antiderivative; this doesn’t exist.
Thus, computing integrals is much simpler to do numerically. This is in stark contrast with differentiation, which is easy to do symbolically but hard numerically.
14.2.4 Numerical integration
Section titled “14.2.4 Numerical integration”Instead of using symbolic computation to get the exact value of an integral, we will resolve to approximation once again. Previously, Theorem 91 showed us that an integral is the limit of the Riemann-sums:
∫ab f(x) dx = limn→∞ ∑i=1n f(ξi) (xi,n − xi−1,n), (14.10)
where Xn = {x0,n,…,xn,n} is a partition of [a,b] and ξi ∈ [xi−1,n,xi,n] are arbitrary intermediate values.
In other words, if n is large enough, the sum ∑ i=1nf(ξi)(xi,n −xi−1,n) is close to ∫ abf(x)dx. There are two crucial issues: first, how to select the partition and the intermediate values; second, how fast is the convergence?
If we want to make (14.11) useful, we have to devise a concrete method that prescribes the xi-s, ξi-s, and tells us how large of an n we should select. This is an extremely rich subject that has been the focus of studies ever since the introduction of integration. So, there is a lot to talk about here. To keep things simple, let’s just focus on the essentials.
The most straightforward method is to select a uniform partition, then approximate the area under the function curve with a sequence of trapezoids.
That is, let X = {a,a +
,a + 2
,…,b} be an equidistant partition, which we’ll use to estimate the integral via calculating the areas determined by the trapezoids given by the partition and the graph, as illustrated in Figure 14.7.

Figure 14.7: Approximating the area under a function with successive trapezoids
As the trapezoid’s area is given by h
, the area under the curve in [xi−1,xi] is approximated by

and we have the approximation

(14.11)
This is the trapezoidal rule. It might seem complicated, but (14.11) is just a weighted sum of the f(xi) values.
Its rate of convergence is quadratic, as stated by the following theorem.
Theorem 97. (Trapezoidal rule)
Let f : [a,b] →ℝ be a twicely differentiable function, and let

be the approximation given by the trapezoidal rule. Then

There are other methods, for instance, Simpson’s rule approximates the function with a piecewise quadratic one. (Instead of a piecewise linear one, like the trapezoidal rule.) Since the approximation is more accurate, the convergence is also faster: Simpson’s rule converges at a O(n−4) rate. Without going into details, it is given by
Sn =
∑i=1⌊n/2⌋ ( f(x2i−2) + 4f(x2i−1) + f(x2i) ), (14.12)
with error

where xi is again the equidistant partition xi = a + i
.
The formula (14.12) can be difficult to unpack, but the essence remains the same: we compute the function’s values at given points, then take their weighted sum.
14.2.5 Implementing the trapezoidal rule
Section titled “14.2.5 Implementing the trapezoidal rule”To show you how straightforward the trapezoidal rule is, let’s implement it in practice! To keep it simple, we are implementing this as a function that takes another function as its input.
def trapezoidal_rule(f, a, b, n): # Define the partition of the interval [a, b] partition = [a + i*(b - a)/n for i in range(n+1)]
# Evaluate the function at each partition point vals = [f(x) for x in partition]
# Apply the trapezoidal rule I_n = (b - a) / (2 * n) * (vals[0] + vals[-1]) + (b - a) / n * sum(vals[1:-1])
return I_nThis can be made even simpler with NumPy, but I’ll leave this to you as an exercise. Let’s test it on an example instead!
With the use of the Newton-Leibniz formula (Theorem 92), you can verify that

(We even computed this with our bare hands, using lower and upper sums.) After plugging the function lambda x: x**2 into trapezoidal_rule, we can see that this method is indeed correct.
import matplotlib.pyplot as plt
with plt.style.context("seaborn-v0_8"): plt.figure() ns = range(1, 25, 1) Is = [trapezoidal_rule(lambda x: x**2, 0, 1, n) for n in ns] plt.axhline(y=1/3, color=’r’, label="the true integral") plt.scatter(ns, Is, label="trapezoidal_rule(f, a, b, n)") plt.ylim([0.3, 0.52]) plt.title("the trapezoidal rule") plt.show()
Figure 14.8: The trapezoidal rule
Bookmark
14.3 Summary
Section titled “14.3 Summary”In this chapter, we have learned about integration, one of the technically most challenging subjects so far. Intuitively, the integral of a function describes the signed area under its graph, but mathematically, it is given by the limit

where a = x0>x1>…>xn = b is a partition of the interval [a,b]. Of course, we don’t often calculate integrals by the definition; we have the Newton-Leibniz formula for that:

where F is the so-called antiderivative, satisfying F′(x) = f(x). This is why integration is thought of as the inverse of differentiation.
As one of my professors used to say, symbolic differentiation is easy, numeric differentiation is hard. It’s the opposite for integrals: symbolic integration is hard, and numeric integration is easy. We’ve learned a couple of tricks to pin down the symbolic part, namely the integration by parts formula
![∫ ∫ b ′ x=b b ′ a f(x)g(x)dx = [f(x)g(x)]x=a − a f(x)g (x)dx](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1420.png)
and the integration by substitution formula

When symbolic integration is hard (and it’s almost always hard), we can resort to numerical methods, such as the Simpson’s rule, given by

Although integration is quite technical and complicated, its proper exposition is extremely important if you want to understand mathematics. The idea of approximating complex shapes with a sequence of rectangles (as shown in Figure 14.3) is the foundation of measure theory, which, in turn, is the foundation of probability theory. (Hell, the idea of approximating complex objects with simpler ones is the foundation of mathematics.)
By now, we have mastered differentiation and integration for single-variable functions. However, univariate functions are rare in practice: in machine learning, we often deal with millions or billions of variables. To handle them in practice, we’ll generalize all we’ve learned to higher dimensions. This is the subject of multivariable calculus, our next big milestone. Let’s get to it!
Bookmark
14.4 Problems
Section titled “14.4 Problems”Problem 1. Use integration by parts to find the following antiderivates.
(a) ∫ sin(x)cos(x)dx (b) ∫ xexdx (c) ∫ x2exdx (d) ∫ ex sinxdx
Problem 2. Use integration by substitution to find the following antiderivatives.
(a) ∫ xcos(x2)dx (b) ∫ sin(x)e{-x2}dx (c) ∫
(d) ∫ x
dx
Problem 3. Let f : [a,b] →ℝ be an integrable function. Show that

Problem 4. Let f,g : [a,b] →ℝ be two integrable functions such that jfj2 and jgj2 are integrable as well. Show that

Hint: revisit Chapter 2 about normed spaces, and find an inequality that feels similar to this one.
Problem 5. The famous Dirichlet function is defined by

Is D(x) integrable?