Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 2.2 — Dot Product, Cosine and Distance
RAG and Vector Search · Example 2 of 2

On unit vectors the three agree

Three ways to compare two vectors: multiply and add (dot product), compare the direction only (cosine), or measure the gap between the points (distance). They rank differently when vectors have different lengths and identically when every vector has length 1.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write cosine(a, b) and distance(a, b) and print both for a = [1, 0], b = [0.6, 0.8] to three decimals. Which is larger, and what does distance^2 equal for these unit vectors?

02

Write rank(query, docs, measure) where docs is a dict of name to vector and measure is "cosine" or "distance". Return names best first. Print the order for the query [1, 0] and docs {"x": [2, 0], "y": [0.5, 0.5]} under both measures.

Explain it without notes

01

What is the difference between the dot product and cosine similarity, and when are they equal?

02

In the example, why does distance rank B first while cosine ranks A first?

03

Why do embedding stores usually let you pick a distance measure when you create an index?

04

A colleague set a similarity threshold of 0.8 and switched the store from cosine to distance, keeping 0.8. What goes wrong?

On unit vectors the three agree
Sign in to run this example in your browser.

Expected output

unit vectors, ranked by dot:      D2, D1, D4, D3
unit vectors, ranked by cosine:   D2, D1, D4, D3
unit vectors, ranked by distance: D2, D1, D4, D3
D1: cosine=0.8000  distance squared=0.4000  2 - 2*cosine=0.4000