A Gaiwan and the Angle Between Teas
The first pour from the gaiwan is floral and brisk; the next is rounder, with a little more sweetness. I want to compare what I taste without pretending that a number can capture the whole cup. So I score three qualities, always in the same order: floral, sweet and bitter.
One infusion gets [4, 2, 1]; another gets [2, 1, 1]. Their scores are different, but their profiles have a similar shape. Cosine similarity measures that resemblance by treating each list as a vector and finding the cosine of the angle between them. In the 1970s, vector-space methods used this idea to compare documents by their term weights. Today, my documents are cups of tea.
package main
import (
"fmt"
"math"
)
func main() {
a, b := []float64{4, 2, 1}, []float64{2, 1, 1}
dot, aa, bb := 0.0, 0.0, 0.0
for i := range a {
dot += a[i] * b[i]; aa += a[i] * a[i]; bb += b[i] * b[i]
}
fmt.Printf("similarity: %.3f\n", dot / (math.Sqrt(aa) * math.Sqrt(bb)))
}
Lua follows the same arithmetic, with indices starting at one:
local a, b = {4, 2, 1}, {2, 1, 1}
local dot, aa, bb = 0, 0, 0
for i = 1, #a do
dot = dot + a[i] * b[i]
aa = aa + a[i] * a[i]
bb = bb + b[i] * b[i]
end
print(string.format("similarity: %.3f", dot / (math.sqrt(aa) * math.sqrt(bb))))
Both print similarity: 0.980. A result of one means the vectors point in exactly the same direction: doubling every score would leave the similarity unchanged. That makes the measure useful for comparing proportions, but it also hides overall strength. A faint cup and a powerful one can score as identical.
For a controlled tasting, keep the leaf, water and pouring method consistent, record intensity separately, and score each attribute on the same scale. The example assumes equal-length vectors with at least one non-zero score apiece; an all-zero tasting has no direction, so its cosine similarity is undefined. The number gives me a prompt to taste again, not a verdict on which infusion is better.