LongMean.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.LongConsumer#accept(long) 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.LongConsumer#accept(long) 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.  * @since 1.1
  51.  */
  52. public final class LongMean implements LongStatistic, StatisticAccumulator<LongMean> {
  53.     /** Limit where the absolute sum can exactly map to a double. Set to 2^53. */
  54.     private static final long SMALL_SUM = 1L << 53;

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

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

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

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

  85.     /**
  86.      * Returns an instance populated using the input {@code values}.
  87.      *
  88.      * @param values Values.
  89.      * @return {@code IntMean} instance.
  90.      */
  91.     public static LongMean of(long... values) {
  92.         final Int128 s = Int128.create();
  93.         for (final long x : values) {
  94.             s.add(x);
  95.         }
  96.         return new LongMean(s, values.length);
  97.     }

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

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

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

  138.     @Override
  139.     public LongMean combine(LongMean other) {
  140.         sum.add(other.sum);
  141.         n += other.n;
  142.         return this;
  143.     }
  144. }