Skip to content
Easy Primitives

Implement Cosine Similarity

Cosine similarity compares the directions of two nonzero vectors. It is their dot product divided by the product of their lengths:

similarity = sum(a * b) / (sqrt(sum(a * a)) * sqrt(sum(b * b)))

For a = [1, 2] and b = [2, 1], the dot product is 4 and each length is sqrt(5). Their similarity is therefore 4 / 5 = 0.8.

In exact arithmetic, the result lies between -1 and 1. A value of 1 means the vectors point in the same direction, 0 means they are perpendicular, and -1 means they point in opposite directions. Positive rescaling does not change the result: [1, 0] and [10, 0] have similarity 1.

Your task

Implement cosine_similarity(a, b) for two nonempty 1D floating-point tensors of the same shape. Return a scalar tensor using the formula above. Use basic tensor operations rather than a built-in cosine-similarity function.

Both vectors have nonzero length. Zero vectors have no direction and are outside this exercise's input contract; you do not need an epsilon rule. Tests use values whose squared sums and denominator are representable. Allow normal floating-point rounding in the result.