SlideIO 2.0.0
Open-source library for reading of medical images
Loading...
Searching...
No Matches
similaritytools.hpp
1// This file is part of slideio project.
2// It is subject to the license terms in the LICENSE file found in the top-level directory
3// of this distribution and at http://slideio.com/license.html.
4#pragma
5
6#include <vector>
7
8namespace slideio
9{
10 class SimilarityTools
11 {
12 public:
13 template <typename Type>
14 static double dotProduct(const std::vector<Type>& a, const std::vector<Type>& b) {
15 // Assuming arrays are of equal length
16 double result = 0.0;
17 for (std::size_t i = 0; i < a.size(); ++i) {
18 result += a[i] * b[i];
19 }
20 return result;
21 }
22
23 template <typename Type>
24 static double magnitude(const std::vector<Type>& v) {
25 double result = 0.0;
26 for (double value : v) {
27 result += value * value;
28 }
29 return sqrt(result);
30 }
31
32 template <typename Type>
33 static double cosineSimilarity(const std::vector<Type>& a, const std::vector<Type>& b) {
34 double dotProd = dotProduct(a, b);
35 double magA = magnitude(a);
36 double magB = magnitude(b);
37 if(magA == 0 && magB == 0) {
38 return 1.0;
39 }
40 else if (magA == 0 || magB == 0) {
41 // Handle division by zero
42 return 0.0;
43 }
44 return dotProd / (magA * magB);
45 }
46 };
47}
Definition: exceptions.hpp:12