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 1 of 2

Three measures, three rankings

Two-number vectors so you can check each result by hand. Real vectors have hundreds of numbers, and the maths is the same.

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?

Three measures, three rankings
Sign in to run this example in your browser.

Expected output

query: [3, 4]  A: [6, 8] (same direction, longer)  B: [4, 3] (close by)  C: [-3, -4] (opposite)
A: dot=50.0 cosine=1.000 distance=5.000
B: dot=24.0 cosine=0.960 distance=1.414
C: dot=-25.0 cosine=-1.000 distance=10.000
ranked by dot:      A, B, C
ranked by cosine:   A, B, C
ranked by distance: B, A, C