首页 > 代码库 > distance

distance

 1 /* 2 * Copyright 2016 E-Tool, Inc. 3 */ 4  5 #ifndef distance_h 6 #define distance_h 7 #include <math.h> 8 #include <vector> 9 using std::vector;10 11 #define max(a,b) (a>b?a:b)12 #define min(a,b) (a<b?a:b)13 14 class Distance {15 public:16     static double euclidean_distance(double x1,double y1,double x2,double y2) {17         return sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));18     }19     static double euclidean_distance(double x1, double y1, double z1, double x2, double y2,  double z2) {20         return sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2)+(z1-z2)*(z1-z2));21     }22     static double euclidean_distance(vector<double> x, vector<double> y) {23         double result = 0;24         for (int i = 0;i < x.size();i++) {25             result += (x[i]-y[i])*(x[i]-y[i]);26         }27         return sqrt(result);28     }29     static double manhattan_distance(double x1, double y1, double x2, double y2) {30         return abs(x1 - x2) + abs(y1 - y2);31     }32     static double manhattan_distance(vector<double> x, vector<double> y) {33         double result = 0;34         for (int i = 0;i < x.size();i++) {35             result += abs(x[i] - y[i]);36         }37         return result;38     }39     static double chebyshev_distance(double x1, double y1, double x2, double y2) {40         return max(abs(x1 - x2) ,abs(y1 - y2));41     }42     static double chebyshev_distance(vector<double> x, vector<double> y) {43         double result=-1;44         for (int i = 0;i < x.size();i++) {45             result = max(result, abs(x[i] - y[i]));46         }47         return result;48     }49     static double minkowski_distance(vector<double> x, vector<double> y,int p) {50         double result = 0;51         for (int i = 0;i < x.size();i++) {52             result += pow(abs(x[i]-y[i]),p);53         }54         return pow(result,1/p);55     }56     /*57     *  Standardized Euclidean distance58     */59     static double standardized_euclidean_distance(vector<double> x, vector<double> y) {60         double result = 0;61         for (int i = 0;i < x.size();i++) {62             double r=(x[i]+y[i])/2;63             double s = (x[i]-r)*(x[i]-r)+(y[i]-r)*(y[i]-r);64             result += (x[i]-y[i])*(x[i]-y[i]) / s;65         }66         return sqrt(result);67     }68     static double information_entropy(vector<double> p) {69         double result=0;70         for (int i = 0;i < p.size();i++) {71             result -= p[i] * (log(p[i])/log(2));72         }73         return result;74     }75 };76 77 #endif

 

distance