# Cosine Similarity

> The Cosine Similarity is a measure of how similar two vectors are, based on the angle between them.

## What is cosine similarity in embeddings?

The measure that compares the directions of two vectors, returning values from '-1' to '1'. Commonly used to compare embeddings: the closer the value to '1', the closer the meanings of the texts.

- Topic: Retrieval
- Type: concept

## Example

Wrong:

```js
function cosine(a, b) {
  const dot = a.reduce((s, x, i) => s + x * b[i], 0);
  const norm = (v) => Math.sqrt(v.reduce((s, x) => s + x * x, 0));
  return dot / (norm(a) * norm(b));
}
```

Right:

```js
function cosine(a, b) {
  if (a.length !== b.length) throw new Error('Vector sizes differ');
  const dot = a.reduce((s, x, i) => s + x * b[i], 0);
  const norm = (v) => Math.sqrt(v.reduce((s, x) => s + x * x, 0));
  const denom = norm(a) * norm(b);
  return denom === 0 ? 0 : dot / denom;
}
```

The fixed version rejects vectors of different sizes and returns 0 for zero vectors instead of `NaN`.

## Common mistakes

- Using a fixed similarity threshold copied from another model.

## Key points

- Vectors that are compared come from the same embedding model.
- If vectors are normalized to length 1, the dot product is used as an equal and faster score.
- Zero vectors are handled so the code does not divide by zero.

## Interview questions

### What is a good cosine similarity score?

It depends on the model. Scores are only comparable within one model, so pick thresholds from your own data.

### Cosine similarity vs dot product?

For vectors normalized to length 1 they give the same ranking. Without normalization, the dot product also grows with vector length.

### What range does cosine similarity have?

From '-1' to '1': '1' means the same direction, '0' means unrelated, and '-1' means opposite.

## Related cards

- [Embeddings](https://wonderium.dev/ai/embeddings.md)
- [Vector Database](https://wonderium.dev/ai/vector-database.md)
- [Semantic Search](https://wonderium.dev/ai/semantic-search.md)

---

- Level: [Artificial Intelligence](https://wonderium.dev/ai.md)
- HTML version: https://wonderium.dev/ai/cosine-similarity
- Last updated: 2026-11-25
