Source : https://www.hackerrank.com/challenges/s10-pearson-correlation-coefficient
Objective
In this challenge, we practice calculating the Pearson correlation coefficient. Check out the Tutorial tab for learning materials!
Task
Given two -element data sets, and , calculate the value of the Pearson correlation coefficient.
Input Format
The first line contains an integer, , denoting the size of data sets and .
The second line contains space-separated real numbers (scaled to at most one decimal place), defining data set .
The third line contains space-separated real numbers (scaled to at most one decimal place), defining data set .
Constraints
- , where is the value of data set .
- , where is the value of data set .
- Data set contains unique values.
- Data set contains unique values.
Output Format
Print the value of the Pearson correlation coefficient, rounded to a scale of decimal places.
Sample Input
10
10 9.8 8 7.8 7.7 7 6 5 4 2
200 44 32 24 22 17 15 12 8 4
Sample Output
0.612Explanation
The mean and standard deviation of data set are:
The mean and standard deviation of data set are:
We use the following formula to calculate the Pearson correlation coefficient:
Source : https://www.hackerrank.com/challenges/s10-pearson-correlation-coefficient
Solution
| // Karthikalapati.blogspot.com | |
| import java.util.Scanner; | |
| public class Solution { | |
| public static void main(String[] args) { | |
| /* Save input */ | |
| Scanner scan = new Scanner(System.in); | |
| int size = scan.nextInt(); | |
| double [] xs = new double[size]; | |
| double [] ys = new double[size]; | |
| for (int i = 0; i < size; i++) { | |
| xs[i] = scan.nextDouble(); | |
| } | |
| for (int i = 0; i < size; i++) { | |
| ys[i] = scan.nextDouble(); | |
| } | |
| scan.close(); | |
| System.out.println(pearson(xs, ys)); | |
| } | |
| /* Calculates Pearson coefficient */ | |
| private static Double pearson(double [] xs, double [] ys) { | |
| if (xs == null || ys == null || xs.length != ys.length) { | |
| return null; | |
| } | |
| double xMean = getMean(xs); | |
| double yMean = getMean(xs); | |
| int n = xs.length; | |
| double numerator = 0; | |
| for (int i = 0; i < n; i++) { | |
| numerator += (xs[i] - xMean) * (ys[i] - yMean); | |
| } | |
| return numerator / (n * standardDeviation(xs) * standardDeviation(ys)); | |
| } | |
| private static Double getMean(double [] array) { | |
| if (array == null) { | |
| return null; | |
| } | |
| double total = 0; | |
| for (double num : array) { | |
| total += num; | |
| } | |
| return total / array.length; | |
| } | |
| private static Double standardDeviation(double [] array) { | |
| if (array == null) { | |
| return null; | |
| } | |
| double mean = getMean(array); | |
| double sum = 0; | |
| for (double x : array) { | |
| sum += Math.pow(x - mean, 2); | |
| } | |
| double variance = sum / array.length; | |
| return Math.sqrt(variance); | |
| } | |
| } | |
No comments:
Post a Comment