用 C++ 找出相关系数的程序
在本教程中,我们将讨论一个用于计算相关系数的程序。
为此,我们将提供两个数组。我们的任务是找出表示给定值之间关系强度的相关系数。
示例
#include<bits/stdc++.h> using namespace std; //function returning correlation coefficient float find_coefficient(int X[], int Y[], int n){ int sum_X = 0, sum_Y = 0, sum_XY = 0; int squareSum_X = 0, squareSum_Y = 0; for (int i = 0; i < n; i++){ sum_X = sum_X + X[i]; sum_Y = sum_Y + Y[i]; sum_XY = sum_XY + X[i] * Y[i]; squareSum_X = squareSum_X + X[i] * X[i]; squareSum_Y = squareSum_Y + Y[i] * Y[i]; } float corr = (float)(n * sum_XY - sum_X * sum_Y) / sqrt((n * squareSum_X - sum_X * sum_X) * (n * squareSum_Y - sum_Y * sum_Y)); return corr; } int main(){ int X[] = {15, 18, 21, 24, 27}; int Y[] = {25, 25, 27, 31, 32}; int n = sizeof(X)/sizeof(X[0]); cout<<find_coefficient(X, Y, n); return 0; }
输出
0.953463
广告