IntMean.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.  * </ul>
  29.  *
  30.  * <p>This class uses an exact integer sum to compute the mean.
  31.  * Supports up to 2<sup>63</sup> (exclusive) observations.
  32.  * This implementation does not check for overflow of the count.
  33.  *
  34.  * <p>This class is designed to work with (though does not require)
  35.  * {@linkplain java.util.stream streams}.
  36.  *
  37.  * <p><strong>This implementation is not thread safe.</strong>
  38.  * If multiple threads access an instance of this class concurrently,
  39.  * and at least one of the threads invokes the {@link java.util.function.IntConsumer#accept(int) accept} or
  40.  * {@link StatisticAccumulator#combine(StatisticResult) combine} method, it must be synchronized externally.
  41.  *
  42.  * <p>However, it is safe to use {@link java.util.function.IntConsumer#accept(int) accept}
  43.  * and {@link StatisticAccumulator#combine(StatisticResult) combine}
  44.  * as {@code accumulator} and {@code combiner} functions of
  45.  * {@link java.util.stream.Collector Collector} on a parallel stream,
  46.  * because the parallel implementation of {@link java.util.stream.Stream#collect Stream.collect()}
  47.  * provides the necessary partitioning, isolation, and merging of results for
  48.  * safe and efficient parallel execution.
  49.  *
  50.  * @see <a href="https://en.wikipedia.org/wiki/Mean">Mean (Wikipedia)</a>
  51.  * @since 1.1 */
  52. public final class IntMean implements IntStatistic, StatisticAccumulator<IntMean> {
  53.     /** Limit for small sample size where the sum can exactly map to a double.
  54.      * This is conservatively set using 2^21 values of 2^31 (2^21 ~ 2 million). */
  55.     private static final long SMALL_N = 1L << 21;

  56.     /** Sum of the values. */
  57.     private final Int128 sum;
  58.     /** Count of values that have been added. */
  59.     private long n;

  60.     /**
  61.      * Create an instance.
  62.      */
  63.     private IntMean() {
  64.         this(Int128.create(), 0);
  65.     }

  66.     /**
  67.      * Create an instance.
  68.      *
  69.      * @param sum Sum of the values.
  70.      * @param n Count of values that have been added.
  71.      */
  72.     private IntMean(Int128 sum, int n) {
  73.         this.sum = sum;
  74.         this.n = n;
  75.     }

  76.     /**
  77.      * Creates an instance.
  78.      *
  79.      * <p>The initial result is {@code NaN}.
  80.      *
  81.      * @return {@code IntMean} instance.
  82.      */
  83.     public static IntMean create() {
  84.         return new IntMean();
  85.     }

  86.     /**
  87.      * Returns an instance populated using the input {@code values}.
  88.      *
  89.      * @param values Values.
  90.      * @return {@code IntMean} instance.
  91.      */
  92.     public static IntMean of(int... values) {
  93.         // Sum of an array cannot exceed a 64-bit long
  94.         long s = 0;
  95.         for (final int x : values) {
  96.             s += x;
  97.         }
  98.         // Convert
  99.         return new IntMean(Int128.of(s), values.length);
  100.     }

  101.     /**
  102.      * Updates the state of the statistic to reflect the addition of {@code value}.
  103.      *
  104.      * @param value Value.
  105.      */
  106.     @Override
  107.     public void accept(int value) {
  108.         sum.add(value);
  109.         n++;
  110.     }

  111.     /**
  112.      * Gets the mean of all input values.
  113.      *
  114.      * <p>When no values have been added, the result is {@code NaN}.
  115.      *
  116.      * @return mean of all values.
  117.      */
  118.     @Override
  119.     public double getAsDouble() {
  120.         return computeMean(sum, n);
  121.     }

  122.     /**
  123.      * Compute the mean.
  124.      *
  125.      * <p>This is a helper method used in higher order moments.
  126.      *
  127.      * @param sum Sum of the values.
  128.      * @param n Count of the values.
  129.      * @return the mean
  130.      */
  131.     static double computeMean(Int128 sum, long n) {
  132.         // Fast option when the sum fits within
  133.         // the mantissa of a double.
  134.         // Handles n=0 as NaN
  135.         if (n < SMALL_N) {
  136.             return (double) sum.lo64() / n;
  137.         }
  138.         // Extended precision
  139.         return IntMath.divide(sum, n);
  140.     }

  141.     @Override
  142.     public IntMean combine(IntMean other) {
  143.         sum.add(other.sum);
  144.         n += other.n;
  145.         return this;
  146.     }
  147. }