# Gox语言中用超大数计算向量的余弦相似度-GX30

``````// 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

calCosSim = func(f1, f2) {
l1 = len(f1)
l2 = len(f2)

if l1 != l2 {
printfln("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 / (math.Sqrt(f1r) * math.Sqrt(f2r))

return rs
}

v1 = [1, 2, 3, 5]
v2 = [2.0, 2, 3, 4]

println(calCosSim(v1, v2))

v3 = [9, 9, 8, 8]
println(calCosSim(v1, v3))

``````

``````λ gox scripts\calCosineSimilarity.gox
0.9756156783416059
0.8556774556139578
``````

``````// 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

// set the short name for math/big package
big = math_big

calCosineSimilarityBig = func(f1, f2) {

l1 = len(f1)
l2 = len(f2)

if l1 != l2 {
printfln("two vectors' length are not same，length of f1: %v，length of f2: %v", l1, l2)
return -1
}

rr = big.NewFloat(0.0)

f1r = big.NewFloat(0.0)

f2r = big.NewFloat(0.0)

for i = 0; i < l1; i++ {
f1Sub = big.NewFloat(f1[i])
f2Sub = big.NewFloat(f2[i])

}

tmp1 = big.NewFloat(0).Mul(big.NewFloat(0).Sqrt(f1r), big.NewFloat(0).Sqrt(f2r))

tmp2 = big.NewFloat(0).Quo(rr, tmp1)

tmp3, _ = tmp2.Float64()

return tmp3
}

v1 = [1, 2, 3, 5]
v2 = [2.0, 2, 3, 4]

println(calCosineSimilarityBig(v1, v2))

v3 = [9, 9, 8, 8]
println(calCosineSimilarityBig(v1, v3))

println("------------")

v1 = [111111, 2222222, 3333333, 55555555555555]
v2 = [2.0, 2, 3, 4]

println(calCosineSimilarityBig(v1, v2))

v3 = [7877358736587356853, 9666666, 8.01, 999999999999]
println(calCosineSimilarityBig(v1, v3))

``````

``````λ gox scripts\calCosineSimilarityBig.gox
0.9756156783416059
0.8556774556139578
------------
0.6963106697792856
1.2894610181964116e-07
``````