CosineDistance.cpp
Go to the documentation of this file.
1 /* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
2 
3 /*
4  QM DSP Library
5 
6  Centre for Digital Music, Queen Mary, University of London.
7  This file copyright 2008 Kurt Jacobson.
8 
9  This program is free software; you can redistribute it and/or
10  modify it under the terms of the GNU General Public License as
11  published by the Free Software Foundation; either version 2 of the
12  License, or (at your option) any later version. See the file
13  COPYING included with this distribution for more information.
14 */
15 
16 #include "CosineDistance.h"
17 
18 #include <iostream>
19 #include <limits>
20 
21 using std::cerr;
22 using std::vector;
23 
24 double CosineDistance::distance(const vector<double> &v1,
25  const vector<double> &v2)
26 {
27  dist = 1.0; dDenTot = 0; dDen1 = 0; dDen2 = 0; dSum1 =0;
28  double small = 1e-20;
29 
30  //check if v1, v2 same size
31  if (v1.size() != v2.size())
32  {
33  cerr << "CosineDistance::distance: ERROR: vectors not the same size\n";
34  return 1.0;
35  }
36  else
37  {
38  for(int i=0; i<int(v1.size()); i++)
39  {
40  dSum1 += v1[i]*v2[i];
41  dDen1 += v1[i]*v1[i];
42  dDen2 += v2[i]*v2[i];
43  }
44  dDenTot = sqrt(fabs(dDen1*dDen2)) + small;
45  dist = 1-((dSum1)/dDenTot);
46  return dist;
47  }
48 }
double distance(const std::vector< double > &v1, const std::vector< double > &v2)