charlang/example/calCosineSimilarity.char
Copy
// work out the cosine similarity of two vectors // the result is in [0..1], which 1 indicates almost the same, 0 indicates not same at all // another way, use the ex module and the math object in it // ex := import("ex") // math := ex.math // rs := rr / (math.sqrt(f1r) * math.sqrt(f2r)) calCosSim := func(f1, f2) { l1 := len(f1) l2 := len(f2) if l1 != l2 { pl("two vectors' length are not same,length of f1: %v,length of f2: %v", l1, l2) return -1 } rr := 0.0 f1r := 0.0 f2r := 0.0 for i := 0; i < l1; i++ { rr += f1[i] * f2[i] f1r += f1[i] * f1[i] f2r += f2[i] * f2[i] } rs := rr / (mathSqrt(f1r) * mathSqrt(f2r)) return rs } v1 := [1, 2, 3, 5] v2 := [2.0, 2, 3, 4] plt(calCosSim(v1, v2)) v3 := [9, 9, 8, 8] plo(calCosSim(v1, v3))