Skip to main content
replaced http://codereview.stackexchange.com/ with https://codereview.stackexchange.com/
Source Link
Added the link to the next iteration.
Source Link
coderodde
  • 32.1k
  • 15
  • 78
  • 205

(See the next iteration.)

I have this funky class method for computing standard deviation from an array of Number objects using the Stream API:

I have this funky class method for computing standard deviation from an array of Number objects using the Stream API:

(See the next iteration.)

I have this funky class method for computing standard deviation from an array of Number objects using the Stream API:

Source Link
coderodde
  • 32.1k
  • 15
  • 78
  • 205

Computing the standard deviation of a Number array in Java

I have this funky class method for computing standard deviation from an array of Number objects using the Stream API:

StandardDeviation.java:

package net.coderodde.util;

import java.util.Arrays;

public class StandardDeviation {

    public static double computeStandardDeviation(Number... collection) {
        if (collection.length == 0) {
            return Double.NaN;
        }

        final double average =
                Arrays.stream(collection)
                      .mapToDouble((x) -> x.doubleValue())
                      .summaryStatistics()
                      .getAverage();

        final double rawSum = 
                Arrays.stream(collection)
                      .mapToDouble((x) -> Math.pow(x.doubleValue() - average,
                                                   2.0))
                      .sum();

        return Math.sqrt(rawSum / (collection.length - 1));
    }

    public static void main(String[] args) {
        // Mix 'em all!
        double sd = computeStandardDeviation((byte) 1, 
                                             (short) 2, 
                                             3, 
                                             4L, 
                                             5.0f, 
                                             6.0);

        System.out.println(sd);
    }
}

Please, tell me anything that comes to mind.