Calculates the mean value for a given set of values. - Java java.lang

Java examples for java.lang:Math Value

Description

Calculates the mean value for a given set of values.

Demo Code

/***************************************************************************
 * Copyright (c) 2016 the WESSBAS project
 *
 * Licensed 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.//from   ww  w. ja  va 2  s  .co m
 ***************************************************************************/
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.LinkedList;
import java.util.List;

public class Main{
    /** Precision of <code>BigDecimal</code> division operations, specifying
     *  the number of digits behind the comma. */
    private final static int PRECISION = 64;
    /**
     * Calculates the mean value for a given set of values.
     *
     * @param values  set of values whose mean value shall be calculated.
     *
     * @return a non-negative mean value.
     */
    public static BigDecimal computeMean(final List<BigDecimal> values) {

        BigDecimal sum = BigDecimal.ZERO;

        for (final BigDecimal value : values) {

            sum = sum.add(value);
        }

        return sum.divide(new BigDecimal(values.size()),
                MathUtil.PRECISION, // must be defined to avoid exceptions;
                BigDecimal.ROUND_HALF_UP);
    }
}

Related Tutorials