Build your own semantic search
Length & normalization·8 min

The L2 norm

0 / 1
# grade this stage (from your course directory)
npx theinference test --stage the-l2-norm --watch

The L2 norm is a vector's length: ‖a‖ = √(Σ aᵢ²). It's the straight-line distance from the origin to the point. We need it to turn raw dot products into angle-based similarity, independent of how long the vectors are.

L2 norm
‖a‖ = √(a₀² + a₁² + … + a₍ₙ₋₁₎²)

What to build

Your task

Implement l2norm

Implement l2norm(a) in src/vecmath.ts: return √(Σ aᵢ²) as a number. Tip: reuse dot — ‖a‖ = √(a·a).

src/vecmath.ts
export function l2norm(a: Float32Array): number {
  // sqrt of the sum of squares — or Math.sqrt(dot(a, a))
}
How it's graded

adapter — allclose vs reference, atol=1e-5, rtol=1e-4, on a seeded vector (your runL2Norm adapter is already wired).

Don't reinvent — compose

Math.sqrt(dot(a, a)) is the whole function. Reusing the dot you just wrote is the point: small pieces compose into the search engine. (Importing dot from the same file is fine; it lives right above.)