Java stddev std(double[] array)

Here you can find the source of std(double[] array)

Description

Returns the standard deviation of an array using the Welford's method.

License

Open Source License

Parameter

Parameter Description
array Input array

Return

Standard deviation

Declaration

public static double std(double[] array) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2016 Pablo Pavon-Marino.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 *
 * Contributors:/*from  w  w w .j  a v a  2  s.  c om*/
 *     Pablo Pavon-Marino - Jose-Luis Izquierdo-Zaragoza, up to version 0.3.1
 *     Pablo Pavon-Marino - from version 0.4.0 onwards
 ******************************************************************************/

import java.util.*;

public class Main {
    /**
     * Returns the standard deviation of an array using the Welford's method.
     *
     * @param array Input array
     * @return Standard deviation
     */
    public static double std(double[] array) {
        if (array.length == 0)
            return 0;

        double M = 0.0;
        double S = 0.0;
        int k = 1;
        for (double value : array) {
            double tmpM = M;
            M += (value - tmpM) / k;
            S += (value - tmpM) * (value - M);
            k++;
        }

        return Math.sqrt(S / (k - 1));
    }

    /**
     * Returns the standard deviation of a collection using the Welford's method.
     *
     * @param collection Collection of numbers
     * @return Standard deviation (or zero, if {@code collection} is empty
     */
    public static double std(Collection<Double> collection) {
        if (collection.isEmpty())
            return 0;

        double M = 0.0;
        double S = 0.0;
        int k = 1;
        for (double value : collection) {
            double tmpM = M;
            M += (value - tmpM) / k;
            S += (value - tmpM) * (value - M);
            k++;
        }

        return Math.sqrt(S / (k - 1));
    }

    /**
     * Returns the standard deviation of values of a map using the Welford's method.
     *
     * @param <A> Key type
     * @param map Input map
     * @return Standard deviation
     */
    public static <A> double std(Map<A, Double> map) {
        return std(map.values());
    }
}

Related

  1. standardDeviation(double[] data, int opt)
  2. std(Collection dist, boolean populationStd)
  3. std(double a[])
  4. std(double[] a)
  5. std(double[] arr)
  6. std(final double[] vec)
  7. std(final double[] x, final int begin, final int end)
  8. std(float[][] arr)
  9. std(long[] array)