Java Variance variance(final double[] values)

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

Description

Computes the (bias-adjusted) variance of the values in the input array.

License

Apache License

Parameter

Parameter Description
values input values

Return

bias-adjusted variance

Declaration

public static double variance(final double[] values) 

Method Source Code

//package com.java2s;
/*//from  w  w w .ja va 2s.c o m
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Main {
    /**
     * Computes the (bias-adjusted) variance of the values in the input array.
     *
     * @param values input values
     * @return bias-adjusted variance
     */
    public static double variance(final double[] values) {
        final int length = values.length;
        final double mean = mean(values);
        double var = Double.NaN;
        if (length == 1) {
            var = 0.0;
        } else if (length > 1) {
            double accum = 0.0;
            double dev = 0.0;
            double accum2 = 0.0;
            for (int i = 0; i < length; i++) {
                dev = values[i] - mean;
                accum += dev * dev;
                accum2 += dev;
            }
            final double len = length;
            var = (accum - (accum2 * accum2 / len)) / (len - 1.0);
        }
        return var;
    }

    /**
     * Computes the mean of the values in the array.
     *
     * @param values input values
     * @return arithmetic mean
     */
    public static double mean(final double[] values) {
        double sum = 0;
        for (double val : values) {
            sum += val;
        }
        return sum / values.length;
    }
}

Related

  1. variance(double[] values)
  2. variance(double[] values, boolean isUnbiased)
  3. variance(double[] vector)
  4. variance(double[] vector)
  5. variance(double[] vector)
  6. variance(final double[] values, final double mean)
  7. variance(final int[] scores)
  8. variance(float[] v, float average)
  9. variance(Integer[] values)