MCPcopy Create free account
hub / github.com/ClickHouse/ai-sdk-cpp / cosine_similarity

Function cosine_similarity

examples/embeddings_example.cpp:26–47  ·  view source on GitHub ↗

Helper function to calculate cosine similarity between two embeddings

Source from the content-addressed store, hash-verified

24
25// Helper function to calculate cosine similarity between two embeddings
26double cosine_similarity(const std::vector<double>& a,
27 const std::vector<double>& b) {
28 if (a.size() != b.size()) {
29 return 0.0;
30 }
31
32 double dot_product = 0.0;
33 double norm_a = 0.0;
34 double norm_b = 0.0;
35
36 for (size_t i = 0; i < a.size(); ++i) {
37 dot_product += a[i] * b[i];
38 norm_a += a[i] * a[i];
39 norm_b += b[i] * b[i];
40 }
41
42 if (norm_a == 0.0 || norm_b == 0.0) {
43 return 0.0;
44 }
45
46 return dot_product / (std::sqrt(norm_a) * std::sqrt(norm_b));
47}
48
49// Helper function to extract embedding as a vector of doubles
50std::vector<double> extract_embedding(const nlohmann::json& data,

Callers 2

TEST_FFunction · 0.85
mainFunction · 0.85

Calls

no outgoing calls

Tested by 1

TEST_FFunction · 0.68