Program to find correlation coefficient

Given two array elements and we have to find the correlation coefficient between two array. Correlation coefficient is an equation that is used to determine the strength of relation between two variables. Correlation coefficient sometimes called as cross correlation coefficient. Correlation coefficient always lies between -1 to +1 where -1 represents X and Y are negatively correlated and +1 represents X and Y are positively correlated.


Where r is correlation coefficient.

Correlation coefficient 
= (5 * 3000 - 105 * 140) 
     / sqrt((5 * 2295 - 1052)*(5*3964 - 1402))
= 300 / sqrt(450 * 220) = 0.953463

Examples –

Input : X[] = {43, 21, 25, 42, 57, 59}
        Y[] = {99, 65, 79, 75, 87, 81}
Output : 0.529809

Input : X[] = {15, 18, 21, 24, 27};
        Y[] = {25, 25, 27, 31, 32}
Output : 0.953463
// <a href="#">Program to find correlation coefficient</a>
#include<bits/stdc++.h>
using namespace std;
// function that returns correlation coefficient.
float correlationCoefficient(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 of elements of array X.
        sum_X = sum_X + X[i];
        // sum of elements of array Y.
        sum_Y = sum_Y + Y[i];
        // sum of X[i] * Y[i].
        sum_XY = sum_XY + X[i] * Y[i];
        // sum of square of array elements.
        squareSum_X = squareSum_X + X[i] * X[i];
        squareSum_Y = squareSum_Y + Y[i] * Y[i];
    }
    // use formula for calculating correlation coefficient.
    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;
}
// Driver function
int main()
{
    int X[] = {15, 18, 21, 24, 27};
    int Y[] = {25, 25, 27, 31, 32};
    //Find the size of array.
    int n = sizeof(X)/sizeof(X[0]);
    //Function call to correlationCoefficient.
    cout<<correlationCoefficient(X, Y, n);
    return 0;
}

Output –

0.953463

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits: http://www.geeksforgeeks.org
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

rakesh

Leave a Reply

Your email address will not be published. Required fields are marked *

Skip to toolbar