Total Pageviews

2018/05/10

[Java] How to compute variance and standard deviation via Java

Problem
Assume I have a List of double, I would like to compute its variance and standard deviation.

How to implement it with Java?

How-To
Here has sample code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
    public static void main(String[] args) {
        List<Double> data = Arrays.asList(0.51, 0.53, 0.49, 0.74, 0.55, 0.47, 0.59, 0.47, 0.45, 0.72);
        DoubleSummaryStatistics summaryStatistics = data.stream().mapToDouble(d -> d.doubleValue()).summaryStatistics();
        Double mean = summaryStatistics.getAverage();

        Double variance = 0d;
        for (Double num : data) {
            variance += Math.pow(num - mean, 2);
        }
        variance = variance / 10;
        Double standardDeviation = Math.sqrt(variance);

        DecimalFormat df = new DecimalFormat("0.000");

        log.info("variance = " + df.format(variance));
        log.info("standardDeviation = " + df.format(standardDeviation));
    }


No comments: