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

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

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

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

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

  171.     @Override
  172.     public LongMean combine(LongMean other) {
  173.         sum.add(other.sum);
  174.         n += other.n;
  175.         return this;
  176.     }
  177. }