Java BigDecimal Calculate calculateArithmeticMean(BigDecimal[] values)

Here you can find the source of calculateArithmeticMean(BigDecimal[] values)

Description

Get the arithmetic mean for a set of values.

License

Apache License

Parameter

Parameter Description
values a parameter

Return

The arithmetic mean.

Declaration

private static BigDecimal calculateArithmeticMean(BigDecimal[] values) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.math.BigDecimal;

public class Main {
    /**/*from www  .  ja  va2  s.  com*/
     * The scale for calculations with BigDecimal.
     */
    private static final int DECIMAL_SCALE = 10;

    /**
     * Get the arithmetic mean for a set of values. Using BigDecimal for exact
     * results.
     * 
     * @param values
     * @return The arithmetic mean.
     */
    private static BigDecimal calculateArithmeticMean(BigDecimal[] values) {
        if (values.length == 1) {
            return values[0].setScale(DECIMAL_SCALE, BigDecimal.ROUND_HALF_UP);
        }
        BigDecimal arithmeticMean = BigDecimal.valueOf(0d);
        for (BigDecimal value : values) {
            arithmeticMean = arithmeticMean.add(value);
        }
        arithmeticMean = arithmeticMean.divide(BigDecimal.valueOf(values.length), DECIMAL_SCALE,
                BigDecimal.ROUND_HALF_UP);
        return arithmeticMean;
    }

    /**
     * Get the arithmetic mean for a set of values. Using BigDecimal for exact
     * results.
     * 
     * @param values
     * @return The arithmetic mean.
     */
    public static double calculateArithmeticMean(double[] values) {
        BigDecimal[] valuesBigD = new BigDecimal[values.length];
        for (int i = 0; i < values.length; i++) {
            valuesBigD[i] = BigDecimal.valueOf(values[i]);
        }
        return calculateArithmeticMean(valuesBigD).doubleValue();
    }
}

Related

  1. calcBMI(BigDecimal lbs, BigDecimal inches)
  2. calcDistance(final BigDecimal x1, final BigDecimal y1, final BigDecimal x2, final BigDecimal y2)
  3. calcPercentage(int priceInCents, BigDecimal vat)
  4. calculate(BigDecimal number1, String operator, BigDecimal number2, int decimalPlaces)
  5. calculateDayRate(BigDecimal rate, BigDecimal money)
  6. calculateDeviation(BigDecimal v1, BigDecimal v2)
  7. calculateDivide(BigDecimal numerator, BigDecimal denominator)
  8. calculateGainPercentage(BigDecimal gain, BigDecimal totalGains)