Computes the variance of the available BigDecimal values. - Java java.math

Java examples for java.math:BigDecimal

Description

Computes the variance of the available BigDecimal values.

Demo Code


//package com.java2s;
import java.math.BigDecimal;

import java.math.MathContext;

import java.util.ArrayList;
import java.util.List;

public class Main {
    /**/*www .  ja va 2 s .c  o  m*/
     * Computes the variance of the available values. By default, the unbiased "sample variance" definitional formula is
     * used: variance = sum((x_i - mean)^2) / (n - 1)
     * <p/>
     * The "population variance"  ( sum((x_i - mean)^2) / n ) can also be computed using this statistic.  The
     * <code>biasCorrected</code> property determines whether the "population" or "sample" value is returned by the
     * <code>evaluate</code> and <code>getResult</code> methods. To compute population variances, set this property to
     * <code>false</code>.
     *
     * @param numbers       the numbers to calculate the variance.
     * @param biasCorrected true if variance is calculated by dividing by n - 1. False if by n.
     * @param context       the MathContext
     * @return the variance of the numbers.
     */
    public static BigDecimal var(List<BigDecimal> numbers,
            boolean biasCorrected, MathContext context) {
        int n = numbers.size();
        if (n == 0) {
            return BigDecimal.valueOf(Double.NaN);
        } else if (n == 1) {
            return BigDecimal.ZERO;
        }
        BigDecimal mean = mean(numbers, context);
        List<BigDecimal> squares = new ArrayList<BigDecimal>();
        for (BigDecimal number : numbers) {
            BigDecimal XminMean = number.subtract(mean);
            squares.add(XminMean.pow(2, context));
        }
        BigDecimal sum = sum(squares);
        return sum.divide(new BigDecimal(biasCorrected ? numbers.size() - 1
                : numbers.size()), context);

    }

    /**
     * Returns the mean number in the numbers list.
     *
     * @param numbers the numbers to calculate the mean.
     * @param context the MathContext.
     * @return the mean of the numbers.
     */
    public static BigDecimal mean(List<BigDecimal> numbers,
            MathContext context) {
        BigDecimal sum = sum(numbers);
        return sum.divide(new BigDecimal(numbers.size()), context);
    }

    /**
     * Returns the sum number in the numbers list.
     *
     * @param numbers the numbers to calculate the sum.
     * @return the sum of the numbers.
     */
    public static BigDecimal sum(List<BigDecimal> numbers) {
        BigDecimal sum = new BigDecimal(0);
        for (BigDecimal bigDecimal : numbers) {
            sum = sum.add(bigDecimal);
        }
        return sum;
    }
}

Related Tutorials