Measure how similar two embeddings are.
What to build
A program that computes the cosine similarity of two vectors.
Requirements
- cos(a, b) = (a · b) / (|a| |b|).
- Print the result with four decimal places.
Input
Two lines: the two vectors (same length, neither all zeros).
Output
One line.
Constraints
At most 1,000 values each.
Example
Input:
1 0
0 1
Output:
0.0000
Why it works
Dividing by the lengths removes the effect of size, so only the angle between the vectors, their direction, matters.
Examples
Example 1 · Input
1 0 0 1
Expected output
0.0000
Example 2 · Input
1 2 3 2 4 6
Expected output
1.0000
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Compute the dot product and the two lengths with math.sqrt.
Hint 2
Divide the dot product by the product of the lengths.
Solution
Show one correct solution (try it yourself first)
import math
a = list(map(float, input().split()))
b = list(map(float, input().split()))
dot = sum(x * y for x, y in zip(a, b))
print(f"{dot / (math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b))) + 0.0:.4f}")