DocWire SDK
DocWire SDK: Deterministic, auditable, and secure data processing in C++20. On-premise by default. No compromises on computational speed.
Loading...
Searching...
No Matches
cosine_similarity.h
1/*********************************************************************************************************************************************/
2/* DocWire SDK: Award-winning modern data processing in C++20. SourceForge Community Choice & Microsoft support. AI-driven processing. */
3/* Supports nearly 100 data formats, including email boxes and OCR. Boost efficiency in text extraction, web data extraction, data mining, */
4/* document analysis. Offline processing possible for security and confidentiality */
5/* */
6/* Copyright (c) SILVERCODERS Ltd, http://silvercoders.com */
7/* Project homepage: https://github.com/docwire/docwire */
8/* */
9/* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-DocWire-Commercial */
10/*********************************************************************************************************************************************/
11
12#ifndef DOCWIRE_COSINE_SIMILARITY_H
13#define DOCWIRE_COSINE_SIMILARITY_H
14
15#include "core_export.h"
16#include <cmath>
17#include <vector>
18#include "error_tags.h"
19#include "throw_if.h"
20
21namespace docwire
22{
23
38inline double cosine_similarity(const std::vector<double>& a, const std::vector<double>& b)
39{
40 DOCWIRE_THROW_IF(a.size() != b.size(), "Vectors must have the same size", errors::program_logic{});
41 double dot_product = 0.0;
42 double norm_a = 0.0;
43 double norm_b = 0.0;
44 for (size_t i = 0; i < a.size(); ++i)
45 {
46 dot_product += a[i] * b[i];
47 norm_a += a[i] * a[i];
48 norm_b += b[i] * b[i];
49 }
50
51 constexpr double zero_vector_threshold_sq = 1e-12;
52 if (norm_a < zero_vector_threshold_sq || norm_b < zero_vector_threshold_sq)
53 return 0.0;
54 return dot_product / (std::sqrt(norm_a) * std::sqrt(norm_b));
55}
56
57} // namespace docwire
58#endif // DOCWIRE_COSINE_SIMILARITY_H
The main namespace for the DocWire SDK.
Definition ai_elements.h:19
double cosine_similarity(const std::vector< double > &a, const std::vector< double > &b)
Calculates the cosine similarity between two vectors.
Program logic failure error tag.
Definition error_tags.h:40