相关系数(皮尔逊相关系数)公式如下
#include <iostream> #include <vector> #include <cmath> using namespace std; // 计算平均值 double mean(vector<double> v) { double sum = 0; for (int i = 0; i < v.size(); i++) { sum += v[i]; } return sum / v.size(); } // 计算协方差 double covariance(vector<double> x, vector<double> y) { double x_mean = mean(x); double y_mean = mean(y); double sum = 0; for (int i = 0; i < x.size(); i++) { sum += (x[i] - x_mean) * (y[i] - y_mean); } return sum / x.size(); } // 计算相关系数 double correlation(vector<double> x, vector<double> y) { double cov = covariance(x, y); double x_std = sqrt(covariance(x, x)); double y_std = sqrt(covariance(y, y)); return cov / (x_std * y_std); } int main() { vector<double> x = { 2, 3, 4, 5, 6}; vector<double> y = { 20, 30, 40, 50, 61}; cout << "Correlation: " << correlation(x, y) << endl; return 0; }View Code
运行结果
标签:std,配准,double,相关系数,C++,vector,sum,mean From: https://www.cnblogs.com/lizhiqiang0204/p/17511694.html