Mean.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.math4.legacy.stat.descriptive.moment;

  18. import org.apache.commons.math4.legacy.exception.MathIllegalArgumentException;
  19. import org.apache.commons.math4.legacy.exception.NullArgumentException;
  20. import org.apache.commons.math4.legacy.stat.descriptive.AbstractStorelessUnivariateStatistic;
  21. import org.apache.commons.math4.legacy.stat.descriptive.WeightedEvaluation;
  22. import org.apache.commons.math4.legacy.stat.descriptive.summary.Sum;
  23. import org.apache.commons.math4.legacy.core.MathArrays;

  24. /**
  25.  * Computes the arithmetic mean of a set of values. Uses the definitional
  26.  * formula:
  27.  * <p>
  28.  * mean = sum(x_i) / n
  29.  * </p>
  30.  * <p>where <code>n</code> is the number of observations.
  31.  * </p>
  32.  * <p>When {@link #increment(double)} is used to add data incrementally from a
  33.  * stream of (unstored) values, the value of the statistic that
  34.  * {@link #getResult()} returns is computed using the following recursive
  35.  * updating algorithm: </p>
  36.  * <ol>
  37.  * <li>Initialize <code>m = </code> the first value</li>
  38.  * <li>For each additional value, update using <br>
  39.  *   <code>m = m + (new value - m) / (number of observations)</code></li>
  40.  * </ol>
  41.  * <p> If {@link #evaluate(double[])} is used to compute the mean of an array
  42.  * of stored values, a two-pass, corrected algorithm is used, starting with
  43.  * the definitional formula computed using the array of stored values and then
  44.  * correcting this by adding the mean deviation of the data values from the
  45.  * arithmetic mean. See, e.g. "Comparison of Several Algorithms for Computing
  46.  * Sample Means and Variances," Robert F. Ling, Journal of the American
  47.  * Statistical Association, Vol. 69, No. 348 (Dec., 1974), pp. 859-866. </p>
  48.  * <p>
  49.  *  Returns <code>Double.NaN</code> if the dataset is empty. Note that
  50.  *  Double.NaN may also be returned if the input includes NaN and / or infinite
  51.  *  values.
  52.  * </p>
  53.  * <strong>Note that this implementation is not synchronized.</strong> If
  54.  * multiple threads access an instance of this class concurrently, and at least
  55.  * one of the threads invokes the <code>increment()</code> or
  56.  * <code>clear()</code> method, it must be synchronized externally.
  57.  */
  58. public class Mean extends AbstractStorelessUnivariateStatistic
  59.     implements WeightedEvaluation {
  60.     /** First moment on which this statistic is based. */
  61.     protected FirstMoment moment;

  62.     /**
  63.      * Determines whether or not this statistic can be incremented or cleared.
  64.      * <p>
  65.      * Statistics based on (constructed from) external moments cannot
  66.      * be incremented or cleared.</p>
  67.      */
  68.     protected boolean incMoment;

  69.     /** Constructs a Mean. */
  70.     public Mean() {
  71.         incMoment = true;
  72.         moment = new FirstMoment();
  73.     }

  74.     /**
  75.      * Constructs a Mean with an External Moment.
  76.      *
  77.      * @param m1 the moment
  78.      */
  79.     public Mean(final FirstMoment m1) {
  80.         this.moment = m1;
  81.         incMoment = false;
  82.     }

  83.     /**
  84.      * Copy constructor, creates a new {@code Mean} identical
  85.      * to the {@code original}.
  86.      *
  87.      * @param original the {@code Mean} instance to copy
  88.      * @throws NullArgumentException if original is null
  89.      */
  90.     public Mean(Mean original) throws NullArgumentException {
  91.         copy(original, this);
  92.     }

  93.     /**
  94.      * {@inheritDoc}
  95.      * <p>Note that when {@link #Mean(FirstMoment)} is used to
  96.      * create a Mean, this method does nothing. In that case, the
  97.      * FirstMoment should be incremented directly.</p>
  98.      */
  99.     @Override
  100.     public void increment(final double d) {
  101.         if (incMoment) {
  102.             moment.increment(d);
  103.         }
  104.     }

  105.     /**
  106.      * {@inheritDoc}
  107.      */
  108.     @Override
  109.     public void clear() {
  110.         if (incMoment) {
  111.             moment.clear();
  112.         }
  113.     }

  114.     /**
  115.      * {@inheritDoc}
  116.      */
  117.     @Override
  118.     public double getResult() {
  119.         return moment.m1;
  120.     }

  121.     /**
  122.      * {@inheritDoc}
  123.      */
  124.     @Override
  125.     public long getN() {
  126.         return moment.getN();
  127.     }

  128.     /**
  129.      * Returns the arithmetic mean of the entries in the specified portion of
  130.      * the input array, or <code>Double.NaN</code> if the designated subarray
  131.      * is empty.
  132.      * <p>
  133.      * Throws <code>IllegalArgumentException</code> if the array is null.</p>
  134.      * <p>
  135.      * See {@link Mean} for details on the computing algorithm.</p>
  136.      *
  137.      * @param values the input array
  138.      * @param begin index of the first array element to include
  139.      * @param length the number of elements to include
  140.      * @return the mean of the values or Double.NaN if length = 0
  141.      * @throws MathIllegalArgumentException if the array is null or the array index
  142.      *  parameters are not valid
  143.      */
  144.     @Override
  145.     public double evaluate(final double[] values, final int begin, final int length)
  146.         throws MathIllegalArgumentException {

  147.         if (MathArrays.verifyValues(values, begin, length)) {
  148.             Sum sum = new Sum();
  149.             double sampleSize = length;

  150.             // Compute initial estimate using definitional formula
  151.             double xbar = sum.evaluate(values, begin, length) / sampleSize;

  152.             // Compute correction factor in second pass
  153.             double correction = 0;
  154.             for (int i = begin; i < begin + length; i++) {
  155.                 correction += values[i] - xbar;
  156.             }
  157.             return xbar + (correction/sampleSize);
  158.         }
  159.         return Double.NaN;
  160.     }

  161.     /**
  162.      * Returns the weighted arithmetic mean of the entries in the specified portion of
  163.      * the input array, or <code>Double.NaN</code> if the designated subarray
  164.      * is empty.
  165.      * <p>
  166.      * Throws <code>IllegalArgumentException</code> if either array is null.</p>
  167.      * <p>
  168.      * See {@link Mean} for details on the computing algorithm. The two-pass algorithm
  169.      * described above is used here, with weights applied in computing both the original
  170.      * estimate and the correction factor.</p>
  171.      * <p>
  172.      * Throws <code>IllegalArgumentException</code> if any of the following are true:
  173.      * <ul><li>the values array is null</li>
  174.      *     <li>the weights array is null</li>
  175.      *     <li>the weights array does not have the same length as the values array</li>
  176.      *     <li>the weights array contains one or more infinite values</li>
  177.      *     <li>the weights array contains one or more NaN values</li>
  178.      *     <li>the weights array contains negative values</li>
  179.      *     <li>the start and length arguments do not determine a valid array</li>
  180.      * </ul>
  181.      *
  182.      * @param values the input array
  183.      * @param weights the weights array
  184.      * @param begin index of the first array element to include
  185.      * @param length the number of elements to include
  186.      * @return the mean of the values or Double.NaN if length = 0
  187.      * @throws MathIllegalArgumentException if the parameters are not valid
  188.      * @since 2.1
  189.      */
  190.     @Override
  191.     public double evaluate(final double[] values, final double[] weights,
  192.                            final int begin, final int length) throws MathIllegalArgumentException {
  193.         if (MathArrays.verifyValues(values, weights, begin, length)) {
  194.             Sum sum = new Sum();

  195.             // Compute initial estimate using definitional formula
  196.             double sumw = sum.evaluate(weights,begin,length);
  197.             double xbarw = sum.evaluate(values, weights, begin, length) / sumw;

  198.             // Compute correction factor in second pass
  199.             double correction = 0;
  200.             for (int i = begin; i < begin + length; i++) {
  201.                 correction += weights[i] * (values[i] - xbarw);
  202.             }
  203.             return xbarw + (correction/sumw);
  204.         }
  205.         return Double.NaN;
  206.     }

  207.     /**
  208.      * Returns the weighted arithmetic mean of the entries in the input array.
  209.      * <p>
  210.      * Throws <code>MathIllegalArgumentException</code> if either array is null.</p>
  211.      * <p>
  212.      * See {@link Mean} for details on the computing algorithm. The two-pass algorithm
  213.      * described above is used here, with weights applied in computing both the original
  214.      * estimate and the correction factor.</p>
  215.      * <p>
  216.      * Throws <code>MathIllegalArgumentException</code> if any of the following are true:
  217.      * <ul><li>the values array is null</li>
  218.      *     <li>the weights array is null</li>
  219.      *     <li>the weights array does not have the same length as the values array</li>
  220.      *     <li>the weights array contains one or more infinite values</li>
  221.      *     <li>the weights array contains one or more NaN values</li>
  222.      *     <li>the weights array contains negative values</li>
  223.      * </ul>
  224.      *
  225.      * @param values the input array
  226.      * @param weights the weights array
  227.      * @return the mean of the values or Double.NaN if length = 0
  228.      * @throws MathIllegalArgumentException if the parameters are not valid
  229.      * @since 2.1
  230.      */
  231.     @Override
  232.     public double evaluate(final double[] values, final double[] weights)
  233.         throws MathIllegalArgumentException {
  234.         return evaluate(values, weights, 0, values.length);
  235.     }

  236.     /**
  237.      * {@inheritDoc}
  238.      */
  239.     @Override
  240.     public Mean copy() {
  241.         Mean result = new Mean();
  242.         // No try-catch or advertised exception because args are guaranteed non-null
  243.         copy(this, result);
  244.         return result;
  245.     }

  246.     /**
  247.      * Copies source to dest.
  248.      * <p>Neither source nor dest can be null.</p>
  249.      *
  250.      * @param source Mean to copy
  251.      * @param dest Mean to copy to
  252.      * @throws NullArgumentException if either source or dest is null
  253.      */
  254.     public static void copy(Mean source, Mean dest)
  255.         throws NullArgumentException {
  256.         NullArgumentException.check(source);
  257.         NullArgumentException.check(dest);
  258.         dest.incMoment = source.incMoment;
  259.         dest.moment = source.moment.copy();
  260.     }
  261. }