LongVariance.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. import java.math.BigInteger;

  19. /**
  20.  * Computes the variance of the available values. The default implementation uses the
  21.  * following definition of the <em>sample variance</em>:
  22.  *
  23.  * <p>\[ \tfrac{1}{n-1} \sum_{i=1}^n (x_i-\overline{x})^2 \]
  24.  *
  25.  * <p>where \( \overline{x} \) is the sample mean, and \( n \) is the number of samples.
  26.  *
  27.  * <ul>
  28.  *   <li>The result is {@code NaN} if no values are added.
  29.  *   <li>The result is zero if there is one value in the data set.
  30.  * </ul>
  31.  *
  32.  * <p>The use of the term \( n − 1 \) is called Bessel's correction. This is an unbiased
  33.  * estimator of the variance of a hypothetical infinite population. If the
  34.  * {@link #setBiased(boolean) biased} option is enabled the normalisation factor is
  35.  * changed to \( \frac{1}{n} \) for a biased estimator of the <em>sample variance</em>.
  36.  *
  37.  * <p>The implementation uses an exact integer sum to compute the scaled (by \( n \))
  38.  * sum of squared deviations from the mean; this is normalised by the scaled correction factor.
  39.  *
  40.  * <p>\[ \frac {n \times \sum_{i=1}^n x_i^2 - (\sum_{i=1}^n x_i)^2}{n \times (n - 1)} \]
  41.  *
  42.  * <p>Supports up to 2<sup>63</sup> (exclusive) observations.
  43.  * This implementation does not check for overflow of the count.
  44.  *
  45.  * <p>This class is designed to work with (though does not require)
  46.  * {@linkplain java.util.stream streams}.
  47.  *
  48.  * <p><strong>This implementation is not thread safe.</strong>
  49.  * If multiple threads access an instance of this class concurrently,
  50.  * and at least one of the threads invokes the {@link java.util.function.LongConsumer#accept(long) accept} or
  51.  * {@link StatisticAccumulator#combine(StatisticResult) combine} method, it must be synchronized externally.
  52.  *
  53.  * <p>However, it is safe to use {@link java.util.function.LongConsumer#accept(long) accept}
  54.  * and {@link StatisticAccumulator#combine(StatisticResult) combine}
  55.  * as {@code accumulator} and {@code combiner} functions of
  56.  * {@link java.util.stream.Collector Collector} on a parallel stream,
  57.  * because the parallel implementation of {@link java.util.stream.Stream#collect Stream.collect()}
  58.  * provides the necessary partitioning, isolation, and merging of results for
  59.  * safe and efficient parallel execution.
  60.  *
  61.  * @see <a href="https://en.wikipedia.org/wiki/variance">variance (Wikipedia)</a>
  62.  * @see <a href="https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance">
  63.  *   Algorithms for computing the variance (Wikipedia)</a>
  64.  * @see <a href="https://en.wikipedia.org/wiki/Bessel%27s_correction">Bessel&#39;s correction</a>
  65.  * @since 1.1
  66.  */
  67. public final class LongVariance implements LongStatistic, StatisticAccumulator<LongVariance> {

  68.     /** Sum of the squared values. */
  69.     private final UInt192 sumSq;
  70.     /** Sum of the values. */
  71.     private final Int128 sum;
  72.     /** Count of values that have been added. */
  73.     private long n;

  74.     /** Flag to control if the statistic is biased, or should use a bias correction. */
  75.     private boolean biased;

  76.     /**
  77.      * Create an instance.
  78.      */
  79.     private LongVariance() {
  80.         this(UInt192.create(), Int128.create(), 0);
  81.     }

  82.     /**
  83.      * Create an instance.
  84.      *
  85.      * @param sumSq Sum of the squared values.
  86.      * @param sum Sum of the values.
  87.      * @param n Count of values that have been added.
  88.      */
  89.     private LongVariance(UInt192 sumSq, Int128 sum, int n) {
  90.         this.sumSq = sumSq;
  91.         this.sum = sum;
  92.         this.n = n;
  93.     }

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

  104.     /**
  105.      * Returns an instance populated using the input {@code values}.
  106.      *
  107.      * @param values Values.
  108.      * @return {@code LongVariance} instance.
  109.      */
  110.     public static LongVariance of(long... values) {
  111.         // Note: Arrays could be processed using specialised counts knowing the maximum limit
  112.         // for an array is 2^31 values. Requires a UInt160.

  113.         final Int128 s = Int128.create();
  114.         final UInt192 ss = UInt192.create();
  115.         for (final long x : values) {
  116.             s.add(x);
  117.             ss.addSquare(x);
  118.         }
  119.         return new LongVariance(ss, s, values.length);
  120.     }

  121.     /**
  122.      * Updates the state of the statistic to reflect the addition of {@code value}.
  123.      *
  124.      * @param value Value.
  125.      */
  126.     @Override
  127.     public void accept(long value) {
  128.         sumSq.addSquare(value);
  129.         sum.add(value);
  130.         n++;
  131.     }

  132.     /**
  133.      * Gets the variance of all input values.
  134.      *
  135.      * <p>When no values have been added, the result is {@code NaN}.
  136.      *
  137.      * @return variance of all values.
  138.      */
  139.     @Override
  140.     public double getAsDouble() {
  141.         return computeVarianceOrStd(sumSq, sum, n, biased, false);
  142.     }

  143.     /**
  144.      * Compute the variance (or standard deviation).
  145.      *
  146.      * <p>The {@code std} flag controls if the result is returned as the standard deviation
  147.      * using the {@link Math#sqrt(double) square root} function.
  148.      *
  149.      * @param sumSq Sum of the squared values.
  150.      * @param sum Sum of the values.
  151.      * @param n Count of values that have been added.
  152.      * @param biased Flag to control if the statistic is biased, or should use a bias correction.
  153.      * @param std Flag to control if the statistic is the standard deviation.
  154.      * @return the variance (or standard deviation)
  155.      */
  156.     static double computeVarianceOrStd(UInt192 sumSq, Int128 sum, long n, boolean biased, boolean std) {
  157.         if (n == 0) {
  158.             return Double.NaN;
  159.         }
  160.         // Avoid a divide by zero
  161.         if (n == 1) {
  162.             return 0;
  163.         }
  164.         // Sum-of-squared deviations: sum(x^2) - sum(x)^2 / n
  165.         // Sum-of-squared deviations precursor: n * sum(x^2) - sum(x)^2
  166.         // The precursor is computed in integer precision.
  167.         // The divide uses double precision.
  168.         // This ensures we avoid cancellation in the difference and use a fast divide.
  169.         // The result is limited to by the rounding in the double computation.
  170.         final double diff = computeSSDevN(sumSq, sum, n);
  171.         final long n0 = biased ? n : n - 1;
  172.         final double v = diff / IntMath.unsignedMultiplyToDouble(n, n0);
  173.         if (std) {
  174.             return Math.sqrt(v);
  175.         }
  176.         return v;
  177.     }

  178.     /**
  179.      * Compute the sum-of-squared deviations multiplied by the count of values:
  180.      * {@code n * sum(x^2) - sum(x)^2}.
  181.      *
  182.      * @param sumSq Sum of the squared values.
  183.      * @param sum Sum of the values.
  184.      * @param n Count of values that have been added.
  185.      * @return the sum-of-squared deviations precursor
  186.      */
  187.     private static double computeSSDevN(UInt192 sumSq, Int128 sum, long n) {
  188.         // Compute the term if possible using fast integer arithmetic.
  189.         // 192-bit sum(x^2) * n will be OK when the upper 32-bits are zero.
  190.         // 128-bit sum(x)^2 will be OK when the upper 64-bits are zero.
  191.         // The first is safe when n < 2^32 but we must check the sum high bits.
  192.         if (((n >>> Integer.SIZE) | sum.hi64()) == 0) {
  193.             return sumSq.unsignedMultiply((int) n).subtract(sum.squareLow()).toDouble();
  194.         } else {
  195.             return sumSq.toBigInteger().multiply(BigInteger.valueOf(n))
  196.                 .subtract(square(sum.toBigInteger())).doubleValue();
  197.         }
  198.     }

  199.     /**
  200.      * Compute the sum of the squared deviations from the mean.
  201.      *
  202.      * <p>This is a helper method used in higher order moments.
  203.      *
  204.      * @return the sum of the squared deviations
  205.      */
  206.     double computeSumOfSquaredDeviations() {
  207.         return computeSSDevN(sumSq, sum, n) / n;
  208.     }

  209.     /**
  210.      * Compute the mean.
  211.      *
  212.      * <p>This is a helper method used in higher order moments.
  213.      *
  214.      * @return the mean
  215.      */
  216.     double computeMean() {
  217.         return LongMean.computeMean(sum, n);
  218.     }

  219.     /**
  220.      * Convenience method to square a BigInteger.
  221.      *
  222.      * @param x Value
  223.      * @return x^2
  224.      */
  225.     private static BigInteger square(BigInteger x) {
  226.         return x.multiply(x);
  227.     }

  228.     @Override
  229.     public LongVariance combine(LongVariance other) {
  230.         sumSq.add(other.sumSq);
  231.         sum.add(other.sum);
  232.         n += other.n;
  233.         return this;
  234.     }

  235.     /**
  236.      * Sets the value of the biased flag. The default value is {@code false}.
  237.      *
  238.      * <p>If {@code false} the sum of squared deviations from the sample mean is normalised by
  239.      * {@code n - 1} where {@code n} is the number of samples. This is Bessel's correction
  240.      * for an unbiased estimator of the variance of a hypothetical infinite population.
  241.      *
  242.      * <p>If {@code true} the sum of squared deviations is normalised by the number of samples
  243.      * {@code n}.
  244.      *
  245.      * <p>Note: This option only applies when {@code n > 1}. The variance of {@code n = 1} is
  246.      * always 0.
  247.      *
  248.      * <p>This flag only controls the final computation of the statistic. The value of this flag
  249.      * will not affect compatibility between instances during a {@link #combine(LongVariance) combine}
  250.      * operation.
  251.      *
  252.      * @param v Value.
  253.      * @return {@code this} instance
  254.      */
  255.     public LongVariance setBiased(boolean v) {
  256.         biased = v;
  257.         return this;
  258.     }
  259. }