RUВход: одна сумма произведений
Два вектора в $\mathbb{R}^4$: $x = (2, 1, 0, 1)$ и $y = (1, 3, 1, 0)$. Насколько они близки по направлению? Нарисовать нельзя — четыре измерения, а посчитать можно: $2\cdot1 + 1\cdot3 + 0\cdot1 + 1\cdot0 = 5$. Это число знает про пару векторов почти всё — длины, угол между ними, ближайшую точку одного на направлении другого и расстояние до этого направления. Весь день про него.
Скалярное произведение
Скалярное произведение$$\langle x, y \rangle = x_1y_1 + x_2y_2 + \cdots + x_ny_n$$Пишут также $x \cdot y$ или $x^{T}y$. Результат — число, а не вектор.
Три свойства, которыми дальше пользуются не задумываясь: симметрия $\langle x,y\rangle = \langle y,x\rangle$; линейность $\langle ax + bz,\ y\rangle = a\langle x,y\rangle + b\langle z,y\rangle$; положительность $\langle x,x\rangle > 0$ при $x \ne 0$. Линейность — разрешение раскрывать скобки как в обычной алгебре, и ниже она понадобится дважды.
Подставим в определение $y = x$: получится $\langle x, x\rangle = x_1^2 + \cdots + x_n^2$, а на плоскости это в точности сумма квадратов катетов для стрелки из начала координат. Значит длина — корень из произведения вектора на себя, и определение переносится в любую размерность.
Евклидова длина (норма)$$\|x\| = \sqrt{\langle x, x\rangle} = \sqrt{x_1^2 + \cdots + x_n^2}$$
Пример. $\|(1,2,3)\| = \sqrt{1 + 4 + 9} = \sqrt{14} \approx 3.7417$.
Ещё две нормы и вопрос про Lasso$\|x\|_1 = |x_1| + \cdots + |x_n|$ — её единичный шар на плоскости ромб с вершинами $(\pm1,0)$ и $(0,\pm1)$; $\|x\|_\infty = \max_i |x_i|$ — шар квадрат со стороной 2. Острые углы ромба у $\|\cdot\|_1$ — причина, по которой L1-регуляризация зануляет коэффициенты модели, а L2 только уменьшает: оптимум чаще попадает в вершину ромба, где часть координат ровно ноль. Дальше в дне везде евклидова норма, её шар — круг.
Угол
Построим треугольник на векторах $x$ и $y$: две стороны — сами векторы, третья — $x - y$. Теорема косинусов даёт $\|x-y\|^2 = \|x\|^2 + \|y\|^2 - 2\|x\|\,\|y\|\cos\varphi$, а линейность — $\|x-y\|^2 = \langle x - y,\ x - y\rangle = \|x\|^2 - 2\langle x,y\rangle + \|y\|^2$. Правые части отличаются ровно одним слагаемым; приравниваем их и сокращаем общее:
Основное равенство дня$$\langle x, y\rangle = \|x\|\,\|y\|\cos\varphi$$Слева координаты, справа геометрия. Читать надо в обе стороны: слева направо оно выдаёт угол по координатам, справа налево — произведение по длинам и углу. Половина задач дня — это второе направление.
Отсюда $\cos\varphi = \dfrac{\langle x, y\rangle}{\|x\|\,\|y\|}$. В $\mathbb{R}^2$ и $\mathbb{R}^3$ это доказанная теорема; в $\mathbb{R}^{100}$ никакого угла заранее не существует, и равенство берут за определение угла. Тогда правая часть обязана лежать в $[-1, 1]$, иначе арккосинуса не будет. Ровно это и гарантирует неравенство, без которого конструкция рассыпалась бы.
Неравенство Коши — Буняковского$$|\langle x, y \rangle| \le \|x\|\,\|y\|$$Равенство достигается тогда и только тогда, когда векторы коллинеарны, то есть один является кратным другого.
Пример. $x = (2,1)$, $y = (1,3)$: произведение равно 5, длины $\sqrt5$ и $\sqrt{10}$, значит $\cos\varphi = \frac{5}{\sqrt{50}} = \frac{1}{\sqrt2} \approx 0.7071$ и $\varphi = \frac{\pi}{4}$.
Три случая, которые читаются вообще без счёта:
| $\langle x,y\rangle$ | Угол | Что это значит |
|---|
| $> 0$ | острый | векторы смотрят примерно в одну сторону |
| $= 0$ | прямой | ортогональны |
| $< 0$ | тупой | смотрят в разные стороны |
Ортогональность — это ровно равенство $\langle x,y\rangle = 0$, и проверяется она одной строкой в любой размерности.
Косинусная близостьПохожесть двух текстов измеряют косинусом угла между их эмбеддингами. Почему не расстоянием? Длина эмбеддинга часто кодирует частотность слова, а не смысл: редкое и частое слово одного значения дадут векторы разной длины, но одного направления. Косинус длину игнорирует. Это готовый ответ на устном туре, произнеси его вслух.
Координаты вместо чертежа
Половина экзаменационных задач про углы формулируется фигурой: куб, квадрат, треугольник. Координат нет — их назначают сами. Приём: поставь удобную вершину в начало координат, направь рёбра по осям, выпиши координаты нужных точек — дальше работает формула косинуса, и никаких теорем о пространственных фигурах не потребуется.
Пример. Из одной вершины единичного куба выходят две диагонали соседних граней. Какой между ними угол? Ставим вершину в начало, рёбра — по осям, диагонали получают координаты $f_1 = (1,1,0)$ и $f_2 = (1,0,1)$, и
$$\cos\varphi = \frac{1 + 0 + 0}{\sqrt2 \cdot \sqrt2} = \frac12 \;\Longrightarrow\; \varphi = 60°$$Тот же ответ даёт стереометрия (концы трёх диагоналей граней из одной вершины попарно удалены на $\sqrt2$, треугольник равносторонний), но догадку надо иметь, а координатный путь требует только аккуратности.
Когда координат нет вовсе
Бывает и наоборот: координат не дают и ввести их негде, а дают длины и углы. Тогда основное равенство читается справа налево, а квадрат нормы раскрывается по линейности:
$$\|u + v\|^2 = \langle u+v,\ u+v\rangle = \|u\|^2 + 2\langle u,v\rangle + \|v\|^2$$Это буквально $(a+b)^2$, где роль удвоенного произведения играет $2\langle u,v\rangle$; для трёх слагаемых добавляются все три попарных произведения.
Пример. $\|u\| = 2$, $\|v\| = 3$, угол $60°$, значит $\langle u,v\rangle = 2\cdot3\cdot\frac12 = 3$, и
$$\|u+v\|^2 = 4 + 9 + 2\cdot 3 = 19 \;\Longrightarrow\; \|u+v\| = \sqrt{19} \approx 4.3589$$Никакой картинки не потребовалось — только раскрытие скобок.
Минус, который теряютПри тупом угле косинус отрицателен, и слагаемое $2\langle u,v\rangle$ уходит в минус. В разности минусов сразу два: $\|u-v\|^2 = \|u\|^2 - 2\langle u,v\rangle + \|v\|^2$, и при тупом угле они гасят друг друга, увеличивая ответ. Бесплатная проверка — неравенство треугольника из блока «Мост»: результат обязан попасть между $\big|\,\|u\|-\|v\|\,\big|$ и $\|u\|+\|v\|$.
Проекция и ортогональная составляющая
Задача. Дан вектор $p$ и направление $v$. Какая точка прямой $\{\lambda v\}$ ближе всего к концу $p$? Ответ — основание перпендикуляра: искомая точка имеет вид $\lambda v$, а разность $p - \lambda v$ ортогональна $v$, то есть даёт нулевое скалярное произведение:
$$\langle p - \lambda v,\ v\rangle = 0 \;\Longrightarrow\; \langle p,v\rangle = \lambda\langle v,v\rangle
\;\Longrightarrow\; \lambda = \frac{\langle p,v\rangle}{\langle v,v\rangle}$$Проекция и ортогональная составляющая$$\proj_v(p) = \frac{\langle p, v\rangle}{\langle v, v\rangle}\,v \qquad \text{— вектор}$$$$\left|\proj_v(p)\right| = \frac{|\langle p, v\rangle|}{\|v\|} \qquad \text{— его длина}$$Остаток $p_\perp = p - \proj_v(p)$ называется ортогональной составляющей, и её длина есть расстояние от конца $p$ до прямой.
Два разных знаменателяСамая частая механическая ошибка темы. В формуле вектора внизу стоит $\langle v,v\rangle = \|v\|^2$, в формуле длины — просто $\|v\|$. Проверка размерностью: вектор обязан содержать множитель $v$, число — не имеет права его содержать.
Вектор $p$ распался на два перпендикулярных куска, поэтому работает Пифагор: $\|p\|^2 = \left|\proj_v(p)\right|^2 + \|p_\perp\|^2$. Отсюда второй способ считать расстояние — не вычитая векторов:
$$d = \sqrt{\|p\|^2 - \left(\frac{\langle p,v\rangle}{\|v\|}\right)^2}$$Три расстояния
До точки: $d = \|p - q\|$. До прямой через начало вдоль $v$: длина ортогональной составляющей, обе формулы выше. До плоскости $\langle n, x\rangle = c$, где $n$ — вектор нормали:
$$d = \frac{|\langle n, p\rangle - c|}{\|n\|}$$Третья формула — та же длина проекции, только на нормаль. Пример. Расстояние от точки $(1,2,3)$ до плоскости $x + 2y + 2z = 6$: нормаль $n = (1,2,2)$ длины 3, значит $d = \frac{|1 + 4 + 6 - 6|}{3} = \frac53 \approx 1.6667$.
Угол как доля направлений
Последний сюжет дня: здесь линейная алгебра смыкается с вероятностью второго дня. Зафиксируем вектор $a$ и посмотрим на знак $\langle \psi, a\rangle$ для всевозможных направлений $\psi$. Плюс — угол острый, минус — тупой, ноль — ровно перпендикуляр. Значит условие $\langle\psi,a\rangle > 0$ вырезает полуплоскость, а на окружности направлений оставляет ровно половину.
Два вектора $a$ и $l$ с углом $\theta$ между ними задают две прямые: $\langle\psi,a\rangle = 0$ перпендикулярна $a$, $\langle\psi,l\rangle = 0$ перпендикулярна $l$, поэтому угол между самими прямыми тоже равен $\theta$. Вместе они режут окружность на четыре дуги: две размера $\theta$, где знаки произведений расходятся, и две размера $\pi - \theta$, где совпадают. Проверка: $2\theta + 2(\pi - \theta) = 2\pi$.
Доля вместо счётаЕсли направление $\psi$ распределено равномерно, то
$$\P(\text{знаки разошлись}) = \frac{2\theta}{2\pi} = \frac{\theta}{\pi}, \qquad
\P(\text{оба произведения} > 0) = \frac{\pi - \theta}{2\pi}$$Никаких интегралов: вероятность — это доля угла, и ответ зависит только от $\theta$.
Три факта превращают это в инструмент для $\mathbb{R}^n$, а не только для плоскости.
Первый. Пусть $\mathcal{L}$ — плоскость, натянутая на $a$ и $l$, а $\psi_1$ — ортогональная проекция $\psi$ на неё. Разность $\psi - \psi_1$ перпендикулярна всей плоскости, а значит и каждому вектору в ней, поэтому $\langle a, \psi\rangle = \langle a, \psi_1\rangle$ и то же для $l$. Проекция сохраняет скалярные произведения с векторами подпространства — поэтому размерность в таких задачах роняют до двух без потери ответа.
Второй. У стандартного нормального вектора (нулевое среднее, единичная матрица ковариаций) проекция на любую плоскость — снова стандартный нормальный вектор, только двумерный, и его направление распределено равномерно по окружности. Поэтому правило доли угла применимо не только к «наудачу выбранному направлению», но и к гауссову вектору.
Третий. В независимых одинаковых испытаниях доля успехов стремится к вероятности успеха в одном испытании (закон больших чисел). Поэтому вопрос «к чему стремится отношение числа очков к числу раундов» — это вопрос о вероятности одного раунда, и больше ничего не нужно.
Что должно остаться в голове
- $\langle x,y\rangle = \sum x_iy_i$ — число; $\|x\| = \sqrt{\langle x,x\rangle}$.
- $\langle x,y\rangle = \|x\|\,\|y\|\cos\varphi$ читается в обе стороны.
- $|\cos\varphi| \le 1$ всегда: получилось больше — арифметическая ошибка, а не открытие.
- Знак произведения — это тип угла, ноль — ортогональность.
- Фигура без координат — поставь вершину в начало и выпиши два вектора.
- Длины и углы без координат — раскрывай квадрат нормы.
- $\proj_v(p) = \frac{\langle p,v\rangle}{\langle v,v\rangle}v$, длина проекции — с $\|v\|$ внизу; остаток $p_\perp$ даёт расстояние, связь между ними — Пифагор.
- Равномерное направление — вероятность есть доля угла; проекция роняет размерность до двух.
ENOpening: one sum of products
Two vectors in $\mathbb{R}^4$: $x = (2, 1, 0, 1)$ and $y = (1, 3, 1, 0)$. How close are they in direction? You cannot draw them — there are four dimensions — but you can calculate: $2\cdot1 + 1\cdot3 + 0\cdot1 + 1\cdot0 = 5$. This number knows almost everything about the pair: their lengths, the angle between them, the nearest point on one along the other’s direction, and the distance to that direction. The entire day is about it.
Dot product
Dot product$$\langle x, y \rangle = x_1y_1 + x_2y_2 + \cdots + x_ny_n$$It is also written $x \cdot y$ or $x^{T}y$. The result is a number, not a vector.
Three properties will be used without further thought: symmetry $\langle x,y\rangle = \langle y,x\rangle$; linearity $\langle ax + bz,\ y\rangle = a\langle x,y\rangle + b\langle z,y\rangle$; and positivity $\langle x,x\rangle > 0$ for $x \ne 0$. Linearity lets you expand brackets as in ordinary algebra, and it will be used twice below.
Set $y = x$ in the definition: $\langle x, x\rangle = x_1^2 + \cdots + x_n^2$. In the plane this is exactly the sum of the squared legs of the arrow from the origin. Thus length is the square root of a vector dotted with itself, and the definition works in any dimension.
Euclidean length (norm)$$\|x\| = \sqrt{\langle x, x\rangle} = \sqrt{x_1^2 + \cdots + x_n^2}$$
Example. $\|(1,2,3)\| = \sqrt{1 + 4 + 9} = \sqrt{14} \approx 3.7417$.
Two more norms and a question about Lasso$\|x\|_1 = |x_1| + \cdots + |x_n|$ has a unit ball that is a rhombus in the plane, with vertices $(\pm1,0)$ and $(0,\pm1)$; $\|x\|_\infty = \max_i |x_i|$ has a square unit ball of side 2. The sharp corners of the $\|\cdot\|_1$ rhombus are why L1 regularization zeros out model coefficients while L2 only shrinks them: the optimum more often lands on a rhombus vertex, where some coordinates are exactly zero. Everywhere else in this day, the norm is Euclidean and its unit ball is a circle.
Angle
Build a triangle from vectors $x$ and $y$: two sides are the vectors themselves, and the third is $x - y$. The law of cosines gives $\|x-y\|^2 = \|x\|^2 + \|y\|^2 - 2\|x\|\,\|y\|\cos\varphi$, while linearity gives $\|x-y\|^2 = \langle x - y,\ x - y\rangle = \|x\|^2 - 2\langle x,y\rangle + \|y\|^2$. The right sides differ in exactly one term; set them equal and cancel the common terms:
The day’s main equality$$\langle x, y\rangle = \|x\|\,\|y\|\cos\varphi$$Coordinates are on the left, geometry on the right. Read it both ways: left to right gives the angle from coordinates, right to left gives a dot product from lengths and an angle. Half of today’s problems use this second direction.
Therefore $\cos\varphi = \dfrac{\langle x, y\rangle}{\|x\|\,\|y\|}$. In $\mathbb{R}^2$ and $\mathbb{R}^3$ this is a proved theorem; in $\mathbb{R}^{100}$ there is no angle in advance, so the equality becomes the definition of an angle. The right-hand side must then lie in $[-1,1]$, or arccosine would not exist. Exactly this is guaranteed by the inequality that keeps the construction from falling apart.
Cauchy–Schwarz inequality$$|\langle x, y \rangle| \le \|x\|\,\|y\|$$Equality holds if and only if the vectors are collinear, that is, one is a scalar multiple of the other.
Example. $x = (2,1)$, $y = (1,3)$: their dot product is 5, their lengths are $\sqrt5$ and $\sqrt{10}$, so $\cos\varphi = \frac{5}{\sqrt{50}} = \frac{1}{\sqrt2} \approx 0.7071$ and $\varphi = \frac\pi4$.
Three cases can be read without any calculation:
| $\langle x,y\rangle$ | Angle | Meaning |
|---|
| $> 0$ | acute | the vectors point roughly in the same direction |
| $= 0$ | right | orthogonal |
| $< 0$ | obtuse | they point in opposite directions |
Orthogonality is exactly $\langle x,y\rangle = 0$, and it can be checked in one line in any dimension.
Cosine similarityThe similarity of two texts is measured by the cosine of the angle between their embeddings. Why not distance? An embedding’s length often encodes word frequency rather than meaning: a rare and a frequent word with the same meaning can produce vectors of different lengths but the same direction. Cosine ignores length. This is a ready-made answer for an oral interview; say it aloud.
Coordinates instead of a diagram
Half of the exam problems about angles are stated as a figure: a cube, square, or triangle. There are no coordinates, so you choose them yourself. Technique: put a convenient vertex at the origin, align edges with the axes, write the coordinates of the points you need, and then use the cosine formula — no spatial-geometry theorem is required.
Example. Two diagonals of adjacent faces leave one vertex of a unit cube. What angle do they form? Put the vertex at the origin and the edges on the axes. The diagonals have coordinates $f_1 = (1,1,0)$ and $f_2 = (1,0,1)$, so
$$\cos\varphi = \frac{1 + 0 + 0}{\sqrt2 \cdot \sqrt2} = \frac12 \;\Longrightarrow\; \varphi = 60°$$Solid geometry gives the same answer (the endpoints of the three face diagonals from one vertex are pairwise $\sqrt2$ apart, forming an equilateral triangle), but that insight must be available; the coordinate route requires only care.
When there are no coordinates at all
The reverse also happens: coordinates are not given and there is nowhere to introduce them, but lengths and angles are provided. Read the main equality right to left, and expand the squared norm by linearity:
$$\|u + v\|^2 = \langle u+v,\ u+v\rangle = \|u\|^2 + 2\langle u,v\rangle + \|v\|^2$$This is literally $(a+b)^2$, with $2\langle u,v\rangle$ playing the role of the doubled product; for three summands, add all three pairwise dot products.
Example. $\|u\| = 2$, $\|v\| = 3$, and the angle is $60°$, so $\langle u,v\rangle = 2\cdot3\cdot\frac12 = 3$, and
$$\|u+v\|^2 = 4 + 9 + 2\cdot 3 = 19 \;\Longrightarrow\; \|u+v\| = \sqrt{19} \approx 4.3589$$No diagram was needed — only expanding brackets.
The minus sign that gets lostFor an obtuse angle, the cosine is negative, so the term $2\langle u,v\rangle$ is negative. In a difference there are two minus signs: $\|u-v\|^2 = \|u\|^2 - 2\langle u,v\rangle + \|v\|^2$, and with an obtuse angle they cancel, increasing the answer. A free check is the triangle inequality from the “Bridge” block: the result must lie between $\big|\,\|u\|-\|v\|\,\big|$ and $\|u\|+\|v\|$.
Projection and the orthogonal component
Problem. Given a vector $p$ and a direction $v$, which point on the line $\{\lambda v\}$ is closest to the endpoint of $p$? It is the foot of the perpendicular: the point has the form $\lambda v$, and the difference $p - \lambda v$ is orthogonal to $v$, so its dot product with $v$ is zero:
$$\langle p - \lambda v,\ v\rangle = 0 \;\Longrightarrow\; \langle p,v\rangle = \lambda\langle v,v\rangle
\;\Longrightarrow\; \lambda = \frac{\langle p,v\rangle}{\langle v,v\rangle}$$Projection and orthogonal component$$\proj_v(p) = \frac{\langle p, v\rangle}{\langle v, v\rangle}\,v \qquad \text{— vector}$$$$\left|\proj_v(p)\right| = \frac{|\langle p, v\rangle|}{\|v\|} \qquad \text{— its length}$$The remainder $p_\perp = p - \proj_v(p)$ is called the orthogonal component, and its length is the distance from the endpoint of $p$ to the line.
Two different denominatorsThis is the most common mechanical error in the topic. In the formula for the vector, the denominator is $\langle v,v\rangle = \|v\|^2$; in the formula for the length, it is simply $\|v\|$. Check dimensions: a vector must contain the factor $v$, while a number must not.
The vector $p$ has split into two perpendicular pieces, so Pythagoras applies: $\|p\|^2 = \left|\proj_v(p)\right|^2 + \|p_\perp\|^2$. This gives a second way to find the distance, without subtracting vectors:
$$d = \sqrt{\|p\|^2 - \left(\frac{\langle p,v\rangle}{\|v\|}\right)^2}$$Three distances
To a point: $d = \|p - q\|$. To a line through the origin along $v$: the length of the orthogonal component, using either formula above. To a plane $\langle n, x\rangle = c$, where $n$ is a normal vector:
$$d = \frac{|\langle n, p\rangle - c|}{\|n\|}$$The third formula is the same projection length, this time onto the normal. Example. Distance from point $(1,2,3)$ to the plane $x + 2y + 2z = 6$: the normal is $n = (1,2,2)$ of length 3, so $d = \frac{|1 + 4 + 6 - 6|}{3} = \frac53 \approx 1.6667$.
Angle as a fraction of directions
The final storyline of the day is where linear algebra meets the probability of Day 2. Fix a vector $a$ and consider the sign of $\langle \psi, a\rangle$ over all possible directions $\psi$. Positive means acute, negative obtuse, and zero exactly perpendicular. Thus $\langle\psi,a\rangle > 0$ cuts out a half-plane, and on the circle of directions it leaves exactly half.
Two vectors $a$ and $l$ with angle $\theta$ between them define two lines: $\langle\psi,a\rangle = 0$ is perpendicular to $a$, and $\langle\psi,l\rangle = 0$ is perpendicular to $l$, so the angle between the lines themselves is also $\theta$. Together they cut the circle into four arcs: two of size $\theta$, where the product signs differ, and two of size $\pi - \theta$, where they agree. Check: $2\theta + 2(\pi - \theta) = 2\pi$.
A fraction instead of countingIf direction $\psi$ is uniformly distributed, then
$$\P(\text{signs differ}) = \frac{2\theta}{2\pi} = \frac{\theta}{\pi}, \qquad
\P(\text{both products} > 0) = \frac{\pi - \theta}{2\pi}$$No integrals: probability is an angular fraction, and the answer depends only on $\theta$.
Three facts turn this into a tool for $\mathbb{R}^n$, not only the plane.
First. Let $\mathcal{L}$ be the plane spanned by $a$ and $l$, and let $\psi_1$ be the orthogonal projection of $\psi$ onto it. The difference $\psi - \psi_1$ is perpendicular to the entire plane, and hence to every vector in it, so $\langle a, \psi\rangle = \langle a, \psi_1\rangle$ and likewise for $l$. Projection preserves dot products with vectors in the subspace — so these problems can be reduced to two dimensions without changing the answer.
Second. A standard normal vector (zero mean, identity covariance matrix) projected onto any plane is again a standard normal vector, now two-dimensional, with its direction uniformly distributed around the circle. Thus the angular-fraction rule applies not only to a direction chosen “at random,” but also to a Gaussian vector.
Third. In independent identically distributed trials, the fraction of successes approaches the probability of success in one trial (the law of large numbers). So asking “what does the ratio of points to rounds tend to?” is asking for the probability of one round, and nothing more is needed.
What should stay in your head
- $\langle x,y\rangle = \sum x_iy_i$ is a number; $\|x\| = \sqrt{\langle x,x\rangle}$.
- $\langle x,y\rangle = \|x\|\,\|y\|\cos\varphi$ can be read both ways.
- $|\cos\varphi| \le 1$ always: if it is larger, the arithmetic is wrong, not the theorem.
- The sign of the dot product identifies the angle; zero means orthogonality.
- A figure with no coordinates: put a vertex at the origin and write two vectors.
- Lengths and angles with no coordinates: expand the squared norm.
- $\proj_v(p) = \frac{\langle p,v\rangle}{\langle v,v\rangle}v$, while the projection length has $\|v\|$ in the denominator; the remainder $p_\perp$ gives the distance, and Pythagoras connects them.
- For a uniform direction, probability is an angular fraction; projection reduces the dimension to two.