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.statistics.descriptive;

  18. /**
  19.  * Computes the arithmetic mean of the available values. Uses the following definition
  20.  * of the <em>sample mean</em>:
  21.  *
  22.  * <p>\[ \frac{1}{n} \sum_{i=1}^n x_i \]
  23.  *
  24.  * <p>where \( n \) is the number of samples.
  25.  *
  26.  * <ul>
  27.  *   <li>The result is {@code NaN} if no values are added.
  28.  *   <li>The result is {@code NaN} if any of the values is {@code NaN}, or the values include
  29.  *       infinite values of opposite sign.
  30.  *   <li>The result is {@code +/-infinity} if values include infinite values of same sign.
  31.  *   <li>The result is finite if all input values are finite.
  32.  * </ul>
  33.  *
  34.  * <p>The {@link #accept(double)} method uses the following recursive updating algorithm
  35.  * that protects the mean from overflow:
  36.  * <ol>
  37.  * <li>Initialize \( m_1 \) using the first value</li>
  38.  * <li>For each additional value, update using <br>
  39.  *     \( m_{i+1} = m_i + (x - m_i) / (i + 1) \)</li>
  40.  * </ol>
  41.  *
  42.  * <p>The {@link #of(double...)} method uses an extended precision sum if the sum is finite.
  43.  * Otherwise uses a corrected two-pass algorithm, starting with
  44.  * the recursive updating algorithm mentioned above, and then correcting this by adding the
  45.  * mean deviation of the data values from the one-pass mean (see Ling (1974)).
  46.  *
  47.  * <p>Supports up to 2<sup>63</sup> (exclusive) observations.
  48.  * This implementation does not check for overflow of the count.
  49.  *
  50.  * <p>This class is designed to work with (though does not require)
  51.  * {@linkplain java.util.stream streams}.
  52.  *
  53.  * <p><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 {@link java.util.function.DoubleConsumer#accept(double) accept} or
  56.  * {@link StatisticAccumulator#combine(StatisticResult) combine} method, it must be synchronized externally.
  57.  *
  58.  * <p>However, it is safe to use {@link java.util.function.DoubleConsumer#accept(double) accept}
  59.  * and {@link StatisticAccumulator#combine(StatisticResult) combine}
  60.  * as {@code accumulator} and {@code combiner} functions of
  61.  * {@link java.util.stream.Collector Collector} on a parallel stream,
  62.  * because the parallel implementation of {@link java.util.stream.Stream#collect Stream.collect()}
  63.  * provides the necessary partitioning, isolation, and merging of results for
  64.  * safe and efficient parallel execution.
  65.  *
  66.  * <p>References:
  67.  * <ul>
  68.  *   <li>Ling, R.F. (1974)
  69.  *       Comparison of Several Algorithms for Computing Sample Means and Variances.
  70.  *       Journal of the American Statistical Association, 69, 859-866.
  71.  *       <a href="https://doi.org/10.2307/2286154">doi: 10.2307/2286154</a>
  72.  * </ul>
  73.  *
  74.  * @see <a href="https://en.wikipedia.org/wiki/Mean">Mean (Wikipedia)</a>
  75.  * @since 1.1
  76.  */
  77. public final class Mean implements DoubleStatistic, StatisticAccumulator<Mean> {

  78.     /**
  79.      * First moment used to compute the mean.
  80.      */
  81.     private final FirstMoment firstMoment;

  82.     /**
  83.      * Create an instance.
  84.      */
  85.     private Mean() {
  86.         this(new FirstMoment());
  87.     }

  88.     /**
  89.      * Creates an instance with a moment.
  90.      *
  91.      * @param m1 First moment.
  92.      */
  93.     Mean(FirstMoment m1) {
  94.         firstMoment = m1;
  95.     }

  96.     /**
  97.      * Creates an instance.
  98.      *
  99.      * <p>The initial result is {@code NaN}.
  100.      *
  101.      * @return {@code Mean} instance.
  102.      */
  103.     public static Mean create() {
  104.         return new Mean();
  105.     }

  106.     /**
  107.      * Returns an instance populated using the input {@code values}.
  108.      *
  109.      * <p>Note: {@code Mean} computed using {@link #accept(double) accept} may be
  110.      * different from this mean.
  111.      *
  112.      * <p>See {@link Mean} for details on the computing algorithm.
  113.      *
  114.      * @param values Values.
  115.      * @return {@code Mean} instance.
  116.      */
  117.     public static Mean of(double... values) {
  118.         return new Mean(FirstMoment.of(values));
  119.     }

  120.     /**
  121.      * Updates the state of the statistic to reflect the addition of {@code value}.
  122.      *
  123.      * @param value Value.
  124.      */
  125.     @Override
  126.     public void accept(double value) {
  127.         firstMoment.accept(value);
  128.     }

  129.     /**
  130.      * Gets the mean of all input values.
  131.      *
  132.      * <p>When no values have been added, the result is {@code NaN}.
  133.      *
  134.      * @return mean of all values.
  135.      */
  136.     @Override
  137.     public double getAsDouble() {
  138.         return firstMoment.getFirstMoment();
  139.     }

  140.     @Override
  141.     public Mean combine(Mean other) {
  142.         firstMoment.combine(other.firstMoment);
  143.         return this;
  144.     }
  145. }