-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspearman.cpp
53 lines (41 loc) · 1.33 KB
/
spearman.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <vector>
#include <algorithm>
// 计算数据排名
std::vector<int> calculateRanks(const std::vector<double>& data) {
int n = data.size();
std::vector<int> ranks(n);
std::vector<std::pair<double, int>> dataWithIndex(n);
for (int i = 0; i < n; ++i) {
dataWithIndex[i] = { data[i], i };
}
std::sort(dataWithIndex.begin(), dataWithIndex.end());
//排名通常从1开始而不是0
for (int i = 0; i < n; ++i) {
ranks[dataWithIndex[i].second] = i + 1;
}
return ranks;
}
// 计算斯皮尔曼相关系数
double spearmanCorrelation(const std::vector<double>& X, const std::vector<double>& Y) {
int n = X.size();
// 计算X和Y的排名
std::vector<int> rankX = calculateRanks(X);
std::vector<int> rankY = calculateRanks(Y);
// 计算排名差的平方和
double dSquaredSum = 0.0;
for (int i = 0; i < n; ++i) {
double d = rankX[i] - rankY[i];
dSquaredSum += d * d;
}
// 计算斯皮尔曼相关系数
double ans = 1 - (6 * dSquaredSum) / (n * (n * n - 1));
return ans;
}
int main() {
std::vector<double> X = { 3,5,1,6,7,2,8,9,4 };
std::vector<double> Y = { 5,3,2,6,8,1,7,9,4 };
double ret = spearmanCorrelation(X, Y);
std::cout << "spearman correlation: " << ret << std::endl;
return 0;
}