Java Variance variance(double[] arr)

Here you can find the source of variance(double[] arr)

Description

Computes and returns the variance.

License

Open Source License

Parameter

Parameter Description
arr a parameter

Declaration

public static double variance(double[] arr) 

Method Source Code

//package com.java2s;
/* ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2014, Numenta, Inc.  Unless you have an agreement
 * with Numenta, Inc., for a separate license for this software code, the
 * following terms and conditions apply:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero Public License for more details.
 *
 * You should have received a copy of the GNU Affero Public License
 * along with this program.  If not, see http://www.gnu.org/licenses.
 *
 * http://numenta.org/licenses///from w w  w  .ja  va2  s  .  c  o  m
 * ---------------------------------------------------------------------
 */

public class Main {
    /**
     * Computes and returns the variance.
     * @param arr
     * @param mean
     * @return
     */
    public static double variance(double[] arr, double mean) {
        double accum = 0.0;
        double dev = 0.0;
        double accum2 = 0.0;
        for (int i = 0; i < arr.length; i++) {
            dev = arr[i] - mean;
            accum += dev * dev;
            accum2 += dev;
        }

        double var = (accum - (accum2 * accum2 / arr.length)) / arr.length;

        return var;
    }

    /**
     * Computes and returns the variance.
     * @param arr
     * @return
     */
    public static double variance(double[] arr) {
        return variance(arr, average(arr));
    }

    /**
     * Returns the average of all the specified array contents.
     * @param arr
     * @return
     */
    public static double average(int[] arr) {
        int sum = 0;
        for (int i = 0; i < arr.length; i++) {
            sum += arr[i];
        }
        return sum / (double) arr.length;
    }

    /**
     * Returns the average of all the specified array contents.
     * @param arr
     * @return
     */
    public static double average(double[] arr) {
        double sum = 0;
        for (int i = 0; i < arr.length; i++) {
            sum += arr[i];
        }
        return sum / (double) arr.length;
    }
}

Related

  1. variance(double... array)
  2. variance(double[] a)
  3. variance(double[] a, int from, int to)
  4. variance(double[] arr)
  5. variance(double[] array)
  6. variance(double[] array)
  7. variance(double[] d)