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.      * Returns an instance populated using the specified range of {@code values}.
  103.      *
  104.      * @param values Values.
  105.      * @param from Inclusive start of the range.
  106.      * @param to Exclusive end of the range.
  107.      * @return {@code IntMean} instance.
  108.      * @throws IndexOutOfBoundsException if the sub-range is out of bounds
  109.      * @since 1.2
  110.      */
  111.     public static IntMean ofRange(int[] values, int from, int to) {
  112.         Statistics.checkFromToIndex(from, to, values.length);
  113.         return createFromRange(values, from, to);
  114.     }

  115.     /**
  116.      * Create an instance using the specified range of {@code values}.
  117.      *
  118.      * <p>Warning: No range checks are performed.
  119.      *
  120.      * @param values Values.
  121.      * @param from Inclusive start of the range.
  122.      * @param to Exclusive end of the range.
  123.      * @return {@code IntMean} instance.
  124.      */
  125.     static IntMean createFromRange(int[] values, int from, int to) {
  126.         // Sum of an array cannot exceed a 64-bit long
  127.         long s = 0;
  128.         for (int i = from; i < to; i++) {
  129.             s += values[i];
  130.         }
  131.         // Convert
  132.         return new IntMean(Int128.of(s), to - from);
  133.     }

  134.     /**
  135.      * Updates the state of the statistic to reflect the addition of {@code value}.
  136.      *
  137.      * @param value Value.
  138.      */
  139.     @Override
  140.     public void accept(int value) {
  141.         sum.add(value);
  142.         n++;
  143.     }

  144.     /**
  145.      * Gets the mean of all input values.
  146.      *
  147.      * <p>When no values have been added, the result is {@code NaN}.
  148.      *
  149.      * @return mean of all values.
  150.      */
  151.     @Override
  152.     public double getAsDouble() {
  153.         return computeMean(sum, n);
  154.     }

  155.     /**
  156.      * Compute the mean.
  157.      *
  158.      * <p>This is a helper method used in higher order moments.
  159.      *
  160.      * @param sum Sum of the values.
  161.      * @param n Count of the values.
  162.      * @return the mean
  163.      */
  164.     static double computeMean(Int128 sum, long n) {
  165.         // Fast option when the sum fits within
  166.         // the mantissa of a double.
  167.         // Handles n=0 as NaN
  168.         if (n < SMALL_N) {
  169.             return (double) sum.lo64() / n;
  170.         }
  171.         // Extended precision
  172.         return sum.divideToDouble(n);
  173.     }

  174.     @Override
  175.     public IntMean combine(IntMean other) {
  176.         sum.add(other.sum);
  177.         n += other.n;
  178.         return this;
  179.     }
  180. }