Pearson productmoment correlation coefficient The Person productmoment correlation coefficient is a measure of linear correlation described well on this Wikipedia page. The formula, is given by: where x and y denote the two vectors between which the correlation is to be measured. Correlation coefficients are used to identify a mutual relationship and/or interdependence between 2 or more variables. Say, you are given a file with N rows, indicating the scores of candidates in three subjects A, B, C (each on a new line, space separated). You need to calculate the pearson coefficients between A and B, B and C, A and C. C++ Program to compute the pearson correlation coefficient between the pairs of variables
Java Program to compute the pearson coefficient between the pairs of variables import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Solution { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); int M[] = new int[n]; int P[] = new int[n]; int C[] = new int[n]; for(int i=0; i<n; i++) { String str[] = br.readLine().split("\t"); M[i] = Integer.parseInt(str[0]); P[i] = Integer.parseInt(str[1]); C[i] = Integer.parseInt(str[2]); } double mp = calculatePearsonProd(M, P); double pc = calculatePearsonProd(P, C); double cm = calculatePearsonProd(C, M); System.out.println(String.format("%.2f", mp)); System.out.println(String.format("%.2f", pc)); System.out.println(String.format("%.2f", cm)); } public static double calculatePearsonProd(int a[], int b[]) { long sumA = sumArray(a); long sumB = sumArray(b); long sumAB = sumProductArray(a, b); long sumA2 = squareSumArray(a); long sumB2 = squareSumArray(b); int n = a.length; double ans = (n*sumAB  sumA*sumB)/(Math.sqrt(n*sumA2  sumA*sumA) * Math.sqrt(n*sumB2  sumB*sumB)); return ans; } public static long sumArray(int a[]) { long sum = 0; for(int i=0; i<a.length; i++) sum += a[i]; return sum; } public static long squareSumArray(int a[]) { long sum = 0; for(int i=0; i<a.length; i++) sum += a[i]*a[i]; return sum; } public static long sumProductArray(int a[], int b[]) { long sum = 0; for(int i=0; i<a.length; i++) sum += a[i]*b[i]; return sum; } } Ruby Program to compute the Pearson Coefficients def pearsonCor (n, x, y, x2, y2, xy) res = (n*xy  x*y).to_f / Math.sqrt(n*x2  x*x) / Math.sqrt(n*y2  y*y) res.round(2) end x = x2 = y = y2 = z = z2 = xy = xz = yz = 0 total = gets.to_i total.times do xi, yi, zi = gets.split(' ').map(&:to_i) x += xi y += yi z += zi x2 += xi*xi y2 += yi*yi z2 += zi*zi xy += xi*yi xz += xi*zi yz += yi*zi end puts pearsonCor(total, x, y, x2, y2, xy) puts pearsonCor (total, z, y, z2, y2, yz) puts pearsonCor (total, x, z, x2, z2, xz) Python Program to compute the pearson coefficient between the pairs of variables

Computer Science >