qm-dsp
1.8
|
00001 /* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */ 00002 00003 /* 00004 QM DSP Library 00005 00006 Centre for Digital Music, Queen Mary, University of London. 00007 This file copyright 2008 Kurt Jacobson. 00008 00009 This program is free software; you can redistribute it and/or 00010 modify it under the terms of the GNU General Public License as 00011 published by the Free Software Foundation; either version 2 of the 00012 License, or (at your option) any later version. See the file 00013 COPYING included with this distribution for more information. 00014 */ 00015 00016 #include "CosineDistance.h" 00017 00018 #include <iostream> 00019 #include <limits> 00020 00021 using std::cerr; 00022 00023 double CosineDistance::distance(const vector<double> &v1, 00024 const vector<double> &v2) 00025 { 00026 dist = 1.0; dDenTot = 0; dDen1 = 0; dDen2 = 0; dSum1 =0; 00027 double small = 1e-20; 00028 00029 //check if v1, v2 same size 00030 if (v1.size() != v2.size()) 00031 { 00032 cerr << "CosineDistance::distance: ERROR: vectors not the same size\n"; 00033 return 1.0; 00034 } 00035 else 00036 { 00037 for(int i=0; i<v1.size(); i++) 00038 { 00039 dSum1 += v1[i]*v2[i]; 00040 dDen1 += v1[i]*v1[i]; 00041 dDen2 += v2[i]*v2[i]; 00042 } 00043 dDenTot = sqrt(fabs(dDen1*dDen2)) + small; 00044 dist = 1-((dSum1)/dDenTot); 00045 return dist; 00046 } 00047 }