Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.util.ArrayList;

import java.util.List;

public class Main {
    public static double calculatePearsonCorrelation(List<Double> list1, List<Double> list2) {
        if (list1.size() != list2.size()) {
            System.err.println("Two lists must have the same dimensionality.");
            return 0;
        }
        double mean1 = calculateMean(list1);
        double mean2 = calculateMean(list2);

        double std1 = Math.sqrt(calculateVariance(list1, mean1));
        double std2 = Math.sqrt(calculateVariance(list2, mean2));

        double dividend = 0;
        for (int i = 0; i < list1.size(); i++) {
            dividend += (list1.get(i) - mean1) * (list2.get(i) - mean2);
        }
        dividend /= list1.size() - 1;

        //System.out.println(mean1+" "+std1+" "+mean2+" "+std2+" "+dividend);
        return dividend / (std1 * std2);
    }

    public static double calculateMean(double[] list) {
        ArrayList<Double> dList = new ArrayList<Double>(list.length);
        for (double d : list)
            dList.add(d);
        return calculateMean(dList);
    }

    public static double calculateMean(List<Double> list) {
        if (list == null || list.size() == 0)
            return Double.MAX_VALUE;
        double sum = 0;
        for (double num : list)
            sum += num;
        return sum / list.size();
    }

    public static double calculateVariance(double[] list, double mean) {
        ArrayList<Double> dList = new ArrayList<Double>(list.length);
        for (double d : list)
            dList.add(d);
        return calculateVariance(dList, mean);
    }

    public static double calculateVariance(List<Double> list, double mean) {
        if (mean == Double.MAX_VALUE)
            return mean;
        if (list.size() == 1)
            return 0;
        double sum = 0;
        for (double num : list) {
            sum += Math.pow(num - mean, 2);
        }
        return sum / (list.size() - 1);
    }
}