5 Euclidean vector spaces

Big data are made up of many numbers in data sets. Such data sets can be represented as vectors in a high dimensional euclidean vector space. A vector is nothing but a list of numbers, but we need to talk mathematically about the size of a vector and perform operations on vectors. The term euclidean refers to vectors with a dot product as known from the plane .
The purpose of this chapter is to set the stage for this, especially by introducing the dot product (or inner product) for general vectors. Having a dot product is immensely useful and we give several applications like linear regression and the perceptron learning algorithm.
In the last part of the chapter we will list rudimentary basics of analysis starting with bounded, open, closed and compact subsets of euclidean spaces leading to continuous functions and the socalled extreme value theorem, Theorem 5.84 . This result states that a huge class of optimization problems always have a solution.
This chapter is also where machine learning begins in earnest. The recipe behind a surprising amount of modern machine learning is: turn your data into vectors, then apply geometry. Measuring distances between vectors gives the nearest neighbor algorithm, the dot product powers the perceptron — the ancestor of modern neural networks — least squares is the mathematics behind linear regression, and the angle between vectors is used to compare texts in natural language processing. All four appear below as live Python code that you are meant to run, break and modify.

5.1 Vectors in the plane

The dot product (or inner product) between two vectors is given by
where
We may also interpret and as matrices (or column vectors). Then the dot product in (5.1) may be realized as the matrix product:
The length or norm of the vector is given by
This follows from the Pythagorean theorem:
The distance between the two vectors and is given by
Also, the cosine of the angle between and is given by
We will not go into this formula. It is a byproduct of considering the projection of a vector on another vector (see Exercise 5.6 ).
All of these rather natural notions in the plane generalize naturally to for .

5.2 Higher dimensions

We denote the set of column vectors with rows by and call it the euclidean vector space of dimension . An element is called a vector and it has the form (column vector with entries)
A vector in is a model for a data set in real life. A collection of numbers, which could signify measurements. You will see an example of this below, where a vector represents a data set counting words in a string.
Being column vectors, vectors in can be added and multiplied by numbers:
The dot product generalizes as follows to higher dimensions.

5.2.1 Dot product, norm and cosine

Suppose that
are vectors in .
  1. The dot product between and is defined by
  2. Two vectors are called orthogonal if . We write this as .
  3. The norm of is defined by
  4. The distance between the two vectors and is defined by
  5. The cosine of the angle between and is defined by
    provided that they both are non-zero.
All of the definitions above are present in modern machine learning frameworks. Below we see their incarnations in the python library numpy.

Live Python

Your first machine learning algorithm

With nothing but the notion of distance we can already build a machine learning algorithm: nearest neighbor classification. We are given data points whose labels we know. A new point is classified by finding the labeled point closest to it and copying its label. Nothing is solved and nothing is trained — the data itself is the model. Try moving the new point below, or add points of your own, and rerun.

Live Python

Nearest neighbor classification is no toy: with enough data it is hard to beat, and it is the reason the distance deserves its central place in this chapter. You meet it every time a streaming service suggests a film. In this setting you are a vector: if the catalogue holds films, a viewer is represented as a point in whose -th coordinate is if the viewer watched film number to the very end and otherwise. With millions of subscribers this gives millions of points in a space of enormous dimension, and two viewers lie close in the distance precisely when they have watched largely the same films. When the service wonders whether to suggest a particular film to you, the picture becomes exactly the code above: the points are the other viewers, labeled blue if they watched that film to the very end and red if they gave up along the way or never watched it at all. You are the new unlabeled point . The service finds the viewers closest to you and copies their label: if your nearest neighbors stayed to the end, the film lands on your front page. Real services refine this picture in two ways: they first compress the enormous viewing-history vectors into learned taste vectors with a few hundred coordinates, and they often measure closeness by the angle between vectors instead of the distance — the cosine similarity you will meet later in this chapter. But the nearest neighbor search itself remains the core, and the mathematics is exactly what you just ran; only the dimension is larger.
Show that
where .
Use the definition in (5.3) to show that
for and .
Let be a nonzero vector and . Use the definition in (5.4) to show that and that
is a unit vector.
You could perhaps use Exercise 5.4 to do this. Notice also that is the absolute value for if .
Given two vectors with , find , such that and are orthogonal, i.e.
This is an equation, where is unknown!
For , it is sketched below that if and are orthogonal, then and are the sides in a right triangle.
In this case, if is the angle between and , show that
Use this to show that
Finally show that
where and are two angles.
In the last question, you could use that the vectors
are unit vectors.
Given two vectors , solve the minimization problem
First convince yourself that minimizes if and only if it minimizes
which happens to be a quadratic polynomial in .

5.3 The unreasonable effectiveness of the dot product

Let denote the distance from to the line through and . What is true about ?

5.3.1 The dist formula from high school

The infamous dist formula from high school says that the distance from the point to the line given by is
Where does this magical formula come from? Consider a general line in parametrized form (see Definition 4.12 )
If , then the distance from to is given by the solution to the optimization problem
This looks scary, but simply boils down to finding the top of a parabola. The solution is
and the point on closest to is .
Now we put (see Example 4.13 )
in order to derive (5.5) . The solution to (5.6) becomes
We must compute the distance from to in this case. The distance squared is
This is a mouthful and I have to admit that I used symbolic software (see below) to verify that

Live Python

5.3.2 The perceptron algorithm

Already at this point we have the necessary definitions for explaining the perceptron algorithm. This is one of the early algorithms of machine learning. It aims at finding a high dimensional line (hyperplane) that separates data organized in two clusters. In terms of the dot product, the idea of the algorithm is described below in dimension two.
A line in the plane is given by an equation
for , where . Given finitely many points
each with a label of (or blue and red for that matter), we wish to find a line (given by ), such that
for . Such a line is called a separating line for the labeled points.
In some cases this is impossible (an example is illustrated below).
Show that it is impossible to find a line separating the red and blue points above. The red points are and . The blue points are and .
A clever approach to finding such a line, if it exists, is to reformulate the problem by looking at the vectors given by
in . Then the existence of the line is equivalent to the existence of a vector with for . If is such a vector, then we have for ,
Therefore we may take and as the line.

A ridiculously simple algorithm

In view of the approach introduced in (5.8) , the following general question is interesting.
Given finitely many vectors , can we find , such that
for every ?
Come up with a simple example, where this problem is unsolvable i.e., come up with vectors , where such an does not exist.
Hint
Try out some simple examples for and .
In case exists, the following ridiculously simple algorithm works in computing . It is called the perceptron (learning) algorithm.
  1. Begin by putting .
  2. If there exists with , then replace by and repeat this step. Otherwise is the desired output vector.
Let us try out the algorithm on the simple example of just two points in given by
In this case the algorithm proceeds as pictured below.
It patiently crawls its way ending with the vector , which satisfies and .
Let us see how (5.7) works in a concrete example.
Consider the points
in , where and are labeled by and is labeled by . Then we let
Now we run the simple algorithm above Example 5.11 :
From the last vector we see that determines a line separating the labeled points.
Below is an implementation of the perceptron (learning) algorithm in python (with numpy) with input from Example 5.12 (it also works in higher dimensions).

Live Python

The algorithm comes alive when you see the line it finds. Below the perceptron runs on two larger clusters and the separating line it computes is drawn through the data. Move the points — or make the clusters overlap and watch what happens to the patiently crawling algorithm (the code gives up after ten thousand rounds; the theorem below explains why it would otherwise never stop).

Live Python

Consider the points
in , where the first point is labeled with and the rest by . Use the perceptron algorithm to compute a separating hyperplane.
What happens when you run the perceptron algorithm on the above points, but where the label of
is changed from to ?

5.3.3 Why does the perceptron algorithm work?

We will assume that there exists , such that
for every . Therefore and if we put
then for every .
The basic insight is the following
Let . After iterations of the perceptron algorithm, satisfies
where is defined in (5.9) .
The algorithm starts with . In the second step we update to if . For such a we have the following inequalities
and
If the second step of the algorithm is executed after steps, then we get for the new that
Proposition 5.14 implies that
Therefore we get and there is an upper bound on the number of iterations used in the second step. So after a finite number of steps, we must have for every .

5.4 Pythagoras and the least squares method

The result below is a generalization of the theorem of Pythagoras about right triangles to higher dimensions.
If and , then
This follows from
since .
The dot product and the norm have a vast number of applications. One of them is the method of least squares: suppose that you are presented with a system
of linear equations, where is an matrix.
You may not be able to solve (5.10) . There could be for example equations and only unknowns making it impossible for all the equations to hold. As an example, the system
of three linear equations and two unknowns does not have any solutions.
The method of (linear) least squares seeks the best approximate solution to (5.10) as a solution to the minimization problem
There is a surprising way of finding optimal solutions to (5.12) :
If is a solution to the system
of linear equations with unknowns, then is an optimal solution to (5.12) . If on the other hand is an optimal solution to (5.12) , then is a solution to (5.13) .
Suppose we know that is orthogonal to for every . Then
for every by Proposition 5.15 . So, in the case that for every we have
for every proving that is an optimal solution to (5.12) .
Now we wish to show that is orthogonal to for every if and only if . This is a computation involving the matrix arithmetic introduced in Chapter 3 :
for every if and only if . But
so that .
On the other hand, if for every , then for every : if we could find with , then
for a small number . This follows, since
which is
By picking sufficiently small,
In a future course on linear algebra you will see that the system of linear equations in Theorem 5.16 is always solvable i.e., an optimal solution to (5.12) can always be found in this way.
Show that (5.11) has no solutions. Compute the best approximate solution to (5.11) using Theorem 5.16 .
The classical application of the least squares method is to find the best line through a given set of points
in the plane .
Usually we cannot find a line matching the points precisely. This corresponds to the fact that the system of equations
has no solutions.
Working with the least squares solution, we try to compute the best line in the sense that
is minimized.
Best fit of line to random points from Wikipedia.
We might as well have asked for the best quadratic polynomial
passing through the points
in .
The same method gives us the system
of linear equations.
Best fit of quadratic polynomial to random points from Wikipedia.
The method generalizes naturally to finding the best polynomial of degree
through a given set of points.
In machine learning the least squares method goes by the name linear regression, and it is the first model most data scientists reach for. The code below carries out the whole computation for the line fit: build the matrix and the vector , solve the normal equations of Theorem 5.16 , and plot the result. Change the points, add noise, add more points — the three lines of code in the middle stay exactly the same; only the data changes.

Live Python

Find the best line through the points and and the best quadratic polynomial through the points and .
It is important here, that you write down the relevant system of linear equations according to Theorem 5.16 . It is however ok to solve the equations on a computer (or check your best fit on WolframAlpha).
Also, you can get a graphical illustration of your result in the python cell below.

Live Python

Lines can also be fitted to data they have no business fitting. The next exercise is a small experiment whose failure is the whole point — remember it when you reach Chapter 7 .
Eight students studied hours for an exam and either failed () or passed ():
Find the best line through these eight points (set up the normal equations from Theorem 5.16 ; solving them on a computer is fine — the cell below plots your line over the data). It is tempting to read the line's value at as "the chance of passing after hours of study". Compute the line's value at and at . Why do the two numbers make that reading absurd? Something better is needed for yes/no data — that something is the sigmoid function, and it arrives in Chapter 7 where these eight students return.

Live Python

A circle with center and radius is given by the equation
  1. Explain how (5.14) can be rewritten to the equation
    where .
  2. Explain how fitting a circle to the points in the least squares context using (5.15) leads to the system
    of linear equations.
  3. Compute the best circle through the points
    by giving the center coordinates and radius with two decimals. Use the python cell below to plot your result too see if it matches the drawing.

Live Python

5.5 The Cauchy-Schwarz inequality

Take another look at (5) in Definition 5.1 . It is actually a small miracle that no matter which (non-zero) vectors and you use as input to the cosine function defined in Example 5.2 , you always get a number between and . The mathematics behind this is rather elegant. It is a consequence of the famous Cauchy-Schwarz inequality stated and proved below.
For two vectors ,
If both sides are , so we may assume . We consider the function given by
Then is a quadratic polynomial with . Therefore its discriminant must be i.e.,
which gives the result.
Why are the two inequalities
a consequence of Theorem 5.24 ?
For arbitrary two numbers ,
since
Why is
for arbitrary numbers ?

5.5.1 The triangle inequality

Another nice consequence of the Cauchy-Schwarz inequality is the triangle inequality.
(5.27) COROLLARY (Triangle inequality). For three vectors ,
From the Cauchy-Schwarz inequality (Theorem 5.24 ) it follows that
for two vectors . Since the right hand side of this inequality is , we have
By the definition of , we then get the desired inequality as
Apply the triangle inequality in the form
for to show that
📖 What to use
Solve it with these results from the book — hover for the statement: 5.15.27

5.5.2 Cosine similarity in machine learning

When two vectors are interpreted as data sets, the number in (5) of Definition 5.1 is known as the cosine similarity. It measures how well the two vectors and point in the same direction: means perfectly aligned, orthogonal, opposite.
A very primitive way of modelling sentences in a language is the socalled one-hot encoding of its words. We will illustrate this by an example. Suppose that our language consists of the words
'a', 'and', 'applicable', 'are', 'fun', 'is', 'mathematics', 'matrices', 'matrix', 'useful'
Each word gets embedded into with a vector associated to its row below
Now consider the two sentences "mathematics is fun and a matrix is useful" and "mathematics is fun and matrices are applicable".
From the words in the two strings we form the following vectors in using the one-hot embedding in (5.16) .
Here a sentence is mapped to the vector, which is the sum of all the vectors corresponding to the words in the sentence, where each vector is multiplied by its multiplicity i.e., how many times the word occurs. The closer the cosine gets to (corresponding to an angle of degrees), the more similar we consider the sentences. Use the python snippet below to experiment and compute the cosine similarity in the example.

Live Python

Cosine similarity is all you need to build a tiny search engine. The code below retrieves the sentences most similar to a query from a small collection of documents (run the cell above first, so that cosinesim is defined — cells on a page share their variables). Scaled up — with better embeddings and billions of documents — this is how retrieval works in modern search engines and in chatbots that look up sources before answering.

Live Python

Use the cell above to compute the cosine similarity between the two one-word sentences "matrix" and "matrices" — and between "fun" and "boring". Explain the outcome. Is it reasonable?
The exercise exposes the fundamental weakness of one-hot encoding: every pair of different words is orthogonal, so "matrix" and "matrices" are judged exactly as unrelated as "matrix" and "banana". The encoding sees spelling, not meaning.
The bread and butter of modern language models is therefore dense embeddings: every word is mapped to a vector with hundreds or thousands of coordinates, learned from enormous amounts of text in such a way that words with similar meaning end up as vectors with high cosine similarity. The breakthrough came in 2013, when Google introduced word2vec. Famously, the learned vectors support a strange arithmetic of meaning:
The cell below shows the mechanics on a hand-made miniature: eight words embedded in , where we have designed the coordinates ourselves to mean (royal, male, female, young, food). Real embeddings are learned, not designed, and their individual coordinates mean nothing to a human — but the geometry works the same way. Compute by hand and check that the ranking below makes sense. Notice one deliberate oddity: apple and banana were given identical coordinates, so their cosine similarity is exactly and the machine literally cannot tell them apart. In a designed embedding that is a decision someone made; the real, learned embedding a few cells below keeps them close but distinguishable. Then invent new words and coordinates of your own.

Live Python

The miniature is a toy, but the real thing is running on this very page: the Ask the book feature of the search palette (press Cmd/Ctrl+K) embeds every passage of this book as a learned vector in , using a small language model called all-MiniLM-L6-v2, and answers a question by cosine-ranking all passages against it — exactly the tiny search engine you built above, at scale. The vectors travel next to this page in the file search-vectors.js, every coordinate stored as an 8-bit integer together with one scaling factor per vector, to keep the download small.
The fold below carries 18 English words embedded by that same model, stored with the same integer trick — open it and you are looking at the actual coordinates: one line per word, 384 small integers each, and a scaling factor per word turning them back into real numbers. Run the cell once; it defines a dictionary E holding the 18 learned vectors in and prints one of them.
Python: 18 words as learned vectors in dimension 384

Live Python

Now the strange arithmetic of meaning can be checked on a real learned embedding, not a designed one. One wrinkle: in a learned embedding the vector is still closest to itself, so it is standard practice to leave the three words of the query out of the ranking. Nobody designed a coordinate to mean royal or female here — 384 learned coordinates, individually meaningless, and yet queen wins. Try the other analogies in the comment, or invent your own from the 18 words.

Live Python

When embedding text one usually considers tokens and not words: every input to a chatbot is broken into a sequence of tokens from a vocabulary of roughly --, and each token is embedded into a euclidean space of dimension well above . The cosine similarity you have computed in this section is, quite literally, the operation used when a chatbot searches a document collection for the passages most relevant to your question.

5.5.3 Attention: the soft nearest neighbor

Inside the chatbot itself, the dot product runs an even bigger show. The T in GPT stands for transformer, and the central mechanism of a transformer is called attention. Here is the problem it solves. A word has one embedded vector, fixed once and for all in a table like the fold above — but meaning is not fixed: "bank" points one way in "the bank of the river" and another in "the bank raised its rates". So the transformer lets every word update its vector by blending in the vectors of the words around it — heavily where the connection is strong, lightly where it is weak. Blending vectors is a weighted average. And the strengths? Dot products, of course.
The recipe is short. Call the vector doing the asking the query , and let be the vectors it may consult. Compute the similarity scores between and each — cosines, as in (5) of Definition 5.1 — and turn the scores into weights by exponentiating and normalizing:
Every weight is positive and together they sum to (make sure you see why), so
is an honest weighted average — the updated vector. The exponential recipe (5.17) is called softmax, and it is one of the workhorses of machine learning. The number is a dial we have added to make the recipe visible; in a real transformer its role is hidden inside learned matrices that reshape every vector before the dot products are taken, but the skeleton is exactly what you see here.
The dial is worth turning, because it explains what attention is. At all the weights are : the update is the plain average, attention spread evenly over everyone. As grows, the largest score soaks up more and more of the weight, and in the limit the weighted average simply becomes the most similar vector — the nearest neighbor from the beginning of this chapter. Softmax attention is a dial between "average of everything" and "winner takes all": a soft nearest neighbor. The cell below turns the 18 embedded words loose on each other. Run it, then change the query and the dial.

Live Python

Read the table: kitten attends to cat, puppy and dog and all but ignores france — and the updated vector has been pulled into the animal corner of (in our run cat tops its similarity ranking). This is the whole trick. In a transformer, every token of your prompt runs this update against every other token, layer after layer, dozens of times, with learned matrices reshaping the vectors between rounds — and out of nothing but dot products, exponentials and weighted averages comes a machine that answers your questions. The mathematics you need in order to train such machinery is the business of Chapter 7, culminating in Section 7.9 — where the softmax recipe will meet you again.
Turn the dial in the cell above.
  1. Set and rerun. Explain every number in the table before you believe it.
  2. Set . Which algorithm from the beginning of this chapter has the cell just reproduced?
  3. Change the query to denmark and find a where copenhagen gets the lion's share of the attention while france and italy still receive visibly more than banana.
The claims made about the dial deserve proofs. Let be the scores in (5.17) .
  1. Show that for all and that , no matter the value of and the signs of the scores.
  2. Suppose for all . Show that as .
Hint
For the second part, divide the numerator and the denominator of by :
Every exponent tends to as , since .

5.6 Special subsets of euclidean spaces

Recall that a circle (or an open disk) centered at with radius is defined as the subset
Similarly an open ball in centered at with radius is defined as the subset
The natural generalization of this definition to higher dimensions is given below.
The open ball centered at with radius is defined as
Why do we need special classes of subsets? The pay-off comes at the end of this chapter: the extreme value theorem (Theorem 5.84 ) guarantees that an optimization problem has a solution when the function is continuous and the constraint set is compact. This section builds the vocabulary needed to state — and appreciate — that theorem: bounded, open, closed and compact subsets. Pay close attention to the logic of the definitions; the quantifiers and from the first chapter do all the heavy lifting here.

5.6.1 Bounded subsets

A subset of is bounded if it does not stretch infinitely far away from the origin — it can be caught inside a large enough open ball centered at :
A subset is called bounded if there exists , such that
(5.34) REMARK (The logic of boundedness). Spelled out with quantifiers, Definition 5.33 says
Read it aloud: there is one radius that works for every point of at the same time. This is where many stumble, because swapping the two quantifiers gives the statement
which is true for every subset whatsoever: given , choose . The swapped statement says nothing — choosing after seeing is cheating. In the definition must be chosen first, and then survive all . The order of and is everything.
For the same reason, showing that a subset is not bounded amounts to proving the negation
i.e., no matter which radius is proposed, some point of escapes the ball.
It does not matter whether we demand or above: if for every , then also for every , and is just another radius. With this in mind, boundedness of is equivalent to each of the following two conditions.
  1. There exists , such that
    for every . This says , which is the same as .
  2. There exists , such that
    for and every i.e., no single coordinate can run off to infinity. Here gives one direction and the other.
Every finite subset is bounded (why?). For , Definition 5.33 simply says
This implies that an interval is bounded by putting in Definition 5.33 .

Chatbot Prompt

I find the definition below quite hard to understand. It is about bounded subsets. Please explain it to me patiently, give some examples and test me afterwards. ''' A subset $S \subseteq \mathbb{R}^n$ is called bounded if there exists $R\in \mathbb{R}$, such that
$$
S \subseteq B(0, R),
$$
where $B(0, R) =  \{v\in \mathbb{R}^n \mid d(0, v) < R\}$ and $d$ is the euclidean distance function. '''
Show precisely that the subset of is not bounded, whereas the subset is.
Hint
Use the negation from Remark 5.34 : given any proposed radius , you must point to a natural number with (this is the archimedean property of the real numbers from the first chapter).
Which of the following subsets are bounded?
Sketch why
is bounded. Now use Fourier-Motzkin elimination to show the same without sketching.

5.6.2 Open, closed and compact subsets and boundaries and interiors of subsets

Open subsets

An open subset of is a subset consisting of points, that are interior in the following sense:
A subset is called open if for every , there exists , such that
Think of an open subset as one where every point has wiggle room: you can move a little in any direction and still stay inside. Notice the quantifiers: this time it is — the wiggle room is allowed to depend on the point (points close to the edge get less of it). Compare with boundedness, where the single had to be chosen before seeing the points.
The interval is an open subset of : for the ball is contained in if we choose — the wiggle room shrinks as approaches or , but it never vanishes.
The interval is not open: the point has no wiggle room at all, since contains negative numbers for every .
The empty set and itself are both open. For , every works at every point. For , the condition is an all-statement over the empty set — true for the same reason that was true in the quiz from the first chapter.
Decide whether each of the subsets given below are open.
  1. (the -axis in )
Prove that an open ball given by is an open subset.
Suppose that . Define a suitable for and use Corollary 5.27 to conclude that .
Show that a finite subset of is never open.
We will need the result below.
If are open subsets, then
are open subsets.
Let . Then for some , and since is open there exists with .
Let . For each there exists with . Put . Then for every , so .
The proposition above concerns finitely many open subsets. Show that
and that is not an open subset of . Where does the proof above break down for infinitely many subsets?

Closed subsets

A subset is called closed if is open.
Closed is not the opposite of open — subsets are not doors. A subset can be both open and closed ( and ), and it can be neither: is not open (no wiggle room at ) and not closed (its complement has no wiggle room at ).
In analogy with Proposition 5.45 we have the result below.
If are closed subsets, then
are closed subsets.
Decide whether each of the subsets given below are closed.

Open intervals

The following subsets
are open subsets of for every .
Let us prove that is an open subset of . If , then we let . Suppose that . If , then and . If , then and therefore and . We have proved that is an open subset.
A similar proof shows that is an open subset. If , then
which is an open subset by the above and Proposition 5.45 .

Closed intervals

We have a similar result for closed subsets.
The following subsets
are closed subsets of for every .
The proof follows from Definition 5.47 and Proposition 5.51 . For example,

Compact subsets

We single out the following very important class of subsets
A subset is called compact if it is bounded and closed.
Compact subsets are the heroes of optimization: a continuous function attains a minimum and a maximum on a compact subset (the extreme value theorem at the end of this chapter). Both halves of the definition are needed, as the following example shows.
The interval is compact: bounded and closed. The interval is bounded but not closed, and the continuous function has no minimum on it: for every there are smaller numbers in , and the natural candidate does not belong to the subset. The subset is closed but not bounded, and has no minimum on it either — this time it escapes to .
Which of the following subsets of are compact?

The boundary of a subset

The boundary of a subset is informally the subset of points barely touching :
This is made precise in the following definition.
The boundary of a subset is defined as
What is the boundary of ? What about ?

The interior of a subset

The interior of a subset consists of the points, which are interior to the subset. More precisely
The interior of a subset is defined by
Prove that the interior of any subset is an open subset. Then show that is open if and only if .
Let and . First make a sketch of these two subsets in and respectively. Then find and .

5.7 Continuous functions

Informally, a function is continuous if small changes of the input produce small changes of the output: the graph has no sudden jumps and can be drawn without lifting the pencil. This matters for optimization. In the real world — and inside a computer — the input is almost never exact: measurements have errors and floating point numbers are rounded. A function you can trust is one where a tiny error in the input cannot cause a violent jump in the output.
The mother of all examples of a function that cannot be trusted is
At the point something dramatic happens: , but arbitrarily close to there are inputs with . An input error of one billionth flips the output from to . It is impossible to plot this function without lifting the pencil. Away from , on the other hand, the function is perfectly harmless.
How do we turn "no jumps" into precise mathematics? Through one of the most important notions in all of analysis — the limit of a function at a point — and a game about error tolerances.

The limit of a function at a point

We want to give precise meaning to the sentence: the values approach as approaches . Remarkably, the point does not even have to belong to the domain of — and this is exactly what makes the notion so useful, as the example below will show. The precise meaning is a game.
(5.61) REMARK (The game). Fix a function , a point and a candidate limit . A skeptic challenges you:
Skeptic: I demand that the output stays within of .
You: Then keep the input within of . I promise that suffices.
You win the round if your delivers: every input within distance of must have within distance of . The limit of at is if you can win every round, no matter how small an the skeptic demands. The smaller the skeptic's , the smaller you will typically have to choose your .
The formal definition is the game in one line.
Let be a function, where and , let and let . We write
and say that has limit as approaches , if
Match the quantifiers in (5.19) with the game: — whatever the skeptic demands; — you have an answer; — and your answer works for every input within . Note who moves first: the skeptic picks before you pick , so your may (and usually does) depend on . Compare with the logic of boundedness in Remark 5.34 : once again the order of the quantifiers is the whole story.
Consider
a function defined on : at both numerator and denominator vanish and the formula breaks down. And yet approaches a definite value as approaches , because
for every . So
and the game is easy to win: if the skeptic demands , answer , since
for every with . Notice that the limit exists even though does not: the limit only speaks about the values of near .
What is
Does exist for the jump function (5.18) ?
Hint
For the jump function: whichever candidate limit is proposed, the skeptic demands . Every -strip around contains inputs with output and inputs with output — can both be within of ?

Continuity

The jump function (5.18) jumps at ; the function in Example 5.63 glides toward a definite value. The notion separating the two is continuity, and with limits in hand it takes one line to define: near , the function must approach exactly the value it takes at .
A function , where and , is called continuous at if
The function is called continuous if it is continuous at every . Unfolded via Definition 5.62 , continuity of at says
i.e., you can win the game with .

Chatbot Prompt

I find the two definitions below (the limit of a function at a point, and continuity) challenging to understand. Please explain them to me patiently with lots of examples, including the interpretation as a game between me and a skeptic. Test me in the end. ''' Let $f: S\rightarrow T$, where $S \subseteq \mathbb{R}^m$ and $T\subseteq \mathbb{R}^d$, let $v\in \mathbb{R}^m$ and $w\in \mathbb{R}^d$. We write $\lim_{u\to v} f(u) = w$ if
$$
\forall \epsilon > 0\, \exists \delta > 0\, \forall u\in S: d(u, v) < \delta \implies d(f(u), w) < \epsilon.
$$
The function $f$ is continuous at $v\in S$ if $\lim_{u\to v} f(u) = f(v)$. '''
The definitions are short and sweet, but take some time to assimilate. You can play the continuity game (the case of the game) in the cell below. The green horizontal band is the skeptic's demand (); the blue vertical strip is your answer (). You win if the graph inside the strip stays inside the band; red dots are inputs that break your promise. For the jump function (5.18) at you lose for every as soon as — try a few! Then change to x**2, where the game can always be won, and play with v, eps and delta.

Live Python

Let us return to the jump function (5.18) and see, formally, how Definition 5.65 kills any hope of it being continuous at . To prove this we must prove that the negation of the proposition in (5.20) is true. This reads
for the function defined in (5.18) . In the language of the game you now play the skeptic: demand . Whatever is offered in reply, the input breaks the promise:
Almost all functions we encounter will be continuous. The function (5.18) is an anomaly — but notice that it is only discontinuous at the single point . At every it is continuous (can you see how to win the game there?).
Let us stop briefly once more and see Definition 5.65 in action.
Let in Definition 5.65 . We consider the two functions
where i.e., is the identity function and is a constant function given by the real number . Both of these functions are continuous. Let us see why.
For the function , (5.20) reads
This is certainly true if we pick : you win the game by echoing the skeptic's demand.
For the function , (5.20) reads
Here can be picked arbitrarily, since is always true — against a constant function the skeptic never stood a chance.
Which of the following statements are true?
If a wins the game for , then the same wins for .
The jump function (5.18) is continuous at .
The jump function (5.18) is continuous at .
In Definition 5.65 , must be chosen before is known.

5.7.1 An elegant way of characterizing a continuous function

Recall the definition of the preimage from Definition 1.115 and the definition of an open subset from Definition 5.39 . The following characterization of continuous functions came rather late in the history of mathematics.
Let be a function. Then is continuous if and only if is open in for every open subset .
Let be an open subset. Assume first that is continuous. We wish to prove that is open. Pick and so that . Now use the continuity of to pick so that (5.20) is satisfied i.e.,
Since , (5.21) says that
showing that is an open subset.
Now suppose that is open whenever is open. For and we put . Since is an open subset, is open and . So we may find so that . But this is exactly the statement that
showing that is continuous.
The following result is often a very useful tool in showing that a subset is closed.
If is a closed subset and a continuous function, then the preimage
is a closed subset of .
If is closed, then is open. Therefore
is open by Proposition 5.68 . This implies that is closed.
Let us assume for now that given by is continuous (see Exercise 5.76 ). Then Proposition 5.69 shows that the subset
of is closed, since is a closed subset of by Proposition 5.52 .
Show formally that the subset
is an open subset of .

5.7.2 Working with continuous functions

We give now three important results, which can be used in concrete situations to verify that a given function is continuous. They can be proved without too much hassle. The first result below basically follows from the definition of the norm of a vector (see (5.4) ).
The projection functions defined in Definition 1.104 are continuous. In general a function is continuous if and only if is continuous for every , where and .
Lemma 5.72 shows for example that the functions and are continuous functions from to .
Consider the vector function given by
as an example. To prove that is continuous, Lemma 5.72 tells us that it is enough to prove that its coordinate functions
are continuous.
Definition 5.65 also behaves nicely when continuous functions are composed. This is the content of the following
Suppose that and are continuous functions, where and . Then the composition
is continuous.
To get continuous functions from functions already known to be continuous using arithmetic operations, the result below is useful.
Let be functions defined on a subset . If and are continuous, then the functions
are continuous functions, where (the last function is defined only if ).
This result is a consequence of the definition of continuity and Proposition 5.74 .
Show in detail that the function given by
is continuous by using Proposition 5.75 combined with Lemma 5.72 .
By combining Example 5.66 with Proposition 5.75 , one finds that every polynomial is a continuous function and that
is continuous for , where .
Verify the claim in Remark 5.77 .
More advanced (transcendental) functions like and also turn out to be continuous. We will return to this in the next chapter, where differentiable functions are defined.
Show from scratch (without using Remark 5.77 ) that
is a continuous function , where and and
Use Proposition 5.52 and Proposition 5.69 to show that
is a closed subset of .
Hint
Write
where is a suitable (closed) interval.
Does
exist? What about

5.8 Important and special results for continuous functions

Below we quote a famous and very intuitive result from 1817 due to Bolzano. This result is also known as the intermediate value theorem.
Let be a continuous function, where . If and , then there exists with , such that .
Python: Bolzano's theorem as an algorithm
The idea behind Bolzano's theorem is not just theory — it is the bisection algorithm for solving equations: cut the interval in half, keep the half where the sign changes, repeat. Below it hunts down a root of , i.e., the cube root of . Fifty halvings of trap the root in an interval of length .

Live Python

Polynomials are continuous functions. Bolzano's result fits perfectly in the proof of the result below. This result is wrong for polynomials in as witnessed by , which does not have a rational root.
Use the methods of Example 1.83 to show that there is no with , where .
Let
be a polynomial of odd degree, i.e. is odd and . Then has a root, i.e. there exists , such that .
We will assume that (if not, just multiply by ). Consider written as
By choosing negative with extremely big, we have , since is negative and
as is positive. Notice here that the terms
are extremely small, when is extremely big.
Similarly by choosing positive and tremendously big, we have . By Theorem 5.81 , there exists with with .
We end this section with a result that might be coined the mathematical cornerstone of optimization (also due to Bolzano, at least for ). The result below is called the extreme value theorem.
Let be a compact subset of and a continuous function. Then there exists , such that
for every .
This is a rather stunning result! You are guaranteed solutions to optimization problems of the type
where is a compact subset and a continuous function. Finding the optimal solutions in this setting is another story. It can be extremely hard. For the rest of these notes we will actually dive into methods for computing optimal solutions of optimization problems such as the one above.
Give two examples, where Theorem 5.84 fails for if we relax the conditions on . One, where is open and another one where is not bounded.