IntVariance.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.IntConsumer#accept(int) 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.IntConsumer#accept(int) 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 IntVariance implements IntStatistic, StatisticAccumulator<IntVariance> {
  68.     /** Small array sample size.
  69.      * Used to avoid computing with UInt96 then converting to UInt128. */
  70.     static final int SMALL_SAMPLE = 10;

  71.     /** Sum of the squared values. */
  72.     private final UInt128 sumSq;
  73.     /** Sum of the values. */
  74.     private final Int128 sum;
  75.     /** Count of values that have been added. */
  76.     private long n;

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

  79.     /**
  80.      * Create an instance.
  81.      */
  82.     private IntVariance() {
  83.         this(UInt128.create(), Int128.create(), 0);
  84.     }

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

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

  107.     /**
  108.      * Returns an instance populated using the input {@code values}.
  109.      *
  110.      * @param values Values.
  111.      * @return {@code IntVariance} instance.
  112.      */
  113.     public static IntVariance of(int... values) {
  114.         // Small arrays can be processed using the object
  115.         if (values.length < SMALL_SAMPLE) {
  116.             final IntVariance stat = new IntVariance();
  117.             for (final int x : values) {
  118.                 stat.accept(x);
  119.             }
  120.             return stat;
  121.         }

  122.         // Arrays can be processed using specialised counts knowing the maximum limit
  123.         // for an array is 2^31 values.
  124.         long s = 0;
  125.         final UInt96 ss = UInt96.create();
  126.         // Process pairs as we know two maximum value int^2 will not overflow
  127.         // an unsigned long.
  128.         final int end = values.length & ~0x1;
  129.         for (int i = 0; i < end; i += 2) {
  130.             final long x = values[i];
  131.             final long y = values[i + 1];
  132.             s += x + y;
  133.             ss.addPositive(x * x + y * y);
  134.         }
  135.         if (end < values.length) {
  136.             final long x = values[end];
  137.             s += x;
  138.             ss.addPositive(x * x);
  139.         }

  140.         // Convert
  141.         return new IntVariance(UInt128.of(ss), Int128.of(s), values.length);
  142.     }

  143.     /**
  144.      * Updates the state of the statistic to reflect the addition of {@code value}.
  145.      *
  146.      * @param value Value.
  147.      */
  148.     @Override
  149.     public void accept(int value) {
  150.         sumSq.addPositive((long) value * value);
  151.         sum.add(value);
  152.         n++;
  153.     }

  154.     /**
  155.      * Gets the variance of all input values.
  156.      *
  157.      * <p>When no values have been added, the result is {@code NaN}.
  158.      *
  159.      * @return variance of all values.
  160.      */
  161.     @Override
  162.     public double getAsDouble() {
  163.         return computeVarianceOrStd(sumSq, sum, n, biased, false);
  164.     }

  165.     /**
  166.      * Compute the variance (or standard deviation).
  167.      *
  168.      * <p>The {@code std} flag controls if the result is returned as the standard deviation
  169.      * using the {@link Math#sqrt(double) square root} function.
  170.      *
  171.      * @param sumSq Sum of the squared values.
  172.      * @param sum Sum of the values.
  173.      * @param n Count of values that have been added.
  174.      * @param biased Flag to control if the statistic is biased, or should use a bias correction.
  175.      * @param std Flag to control if the statistic is the standard deviation.
  176.      * @return the variance (or standard deviation)
  177.      */
  178.     static double computeVarianceOrStd(UInt128 sumSq, Int128 sum, long n, boolean biased, boolean std) {
  179.         if (n == 0) {
  180.             return Double.NaN;
  181.         }
  182.         // Avoid a divide by zero
  183.         if (n == 1) {
  184.             return 0;
  185.         }
  186.         // Sum-of-squared deviations: sum(x^2) - sum(x)^2 / n
  187.         // Sum-of-squared deviations precursor: n * sum(x^2) - sum(x)^2
  188.         // The precursor is computed in integer precision.
  189.         // The divide uses double precision.
  190.         // This ensures we avoid cancellation in the difference and use a fast divide.
  191.         // The result is limited to by the rounding in the double computation.
  192.         final double diff = computeSSDevN(sumSq, sum, n);
  193.         final long n0 = biased ? n : n - 1;
  194.         final double v = diff / IntMath.unsignedMultiplyToDouble(n, n0);
  195.         if (std) {
  196.             return Math.sqrt(v);
  197.         }
  198.         return v;
  199.     }

  200.     /**
  201.      * Compute the sum-of-squared deviations multiplied by the count of values:
  202.      * {@code n * sum(x^2) - sum(x)^2}.
  203.      *
  204.      * @param sumSq Sum of the squared values.
  205.      * @param sum Sum of the values.
  206.      * @param n Count of values that have been added.
  207.      * @return the sum-of-squared deviations precursor
  208.      */
  209.     private static double computeSSDevN(UInt128 sumSq, Int128 sum, long n) {
  210.         // Compute the term if possible using fast integer arithmetic.
  211.         // 128-bit sum(x^2) * n will be OK when the upper 32-bits are zero.
  212.         // 128-bit sum(x)^2 will be OK when the upper 64-bits are zero.
  213.         // Both are safe when n < 2^32.
  214.         if ((n >>> Integer.SIZE) == 0) {
  215.             return sumSq.unsignedMultiply((int) n).subtract(sum.squareLow()).toDouble();
  216.         } else {
  217.             return sumSq.toBigInteger().multiply(BigInteger.valueOf(n))
  218.                 .subtract(square(sum.toBigInteger())).doubleValue();
  219.         }
  220.     }

  221.     /**
  222.      * Compute the sum of the squared deviations from the mean.
  223.      *
  224.      * <p>This is a helper method used in higher order moments.
  225.      *
  226.      * @return the sum of the squared deviations
  227.      */
  228.     double computeSumOfSquaredDeviations() {
  229.         return computeSSDevN(sumSq, sum, n) / n;
  230.     }

  231.     /**
  232.      * Compute the mean.
  233.      *
  234.      * <p>This is a helper method used in higher order moments.
  235.      *
  236.      * @return the mean
  237.      */
  238.     double computeMean() {
  239.         return IntMean.computeMean(sum, n);
  240.     }

  241.     /**
  242.      * Convenience method to square a BigInteger.
  243.      *
  244.      * @param x Value
  245.      * @return x^2
  246.      */
  247.     private static BigInteger square(BigInteger x) {
  248.         return x.multiply(x);
  249.     }

  250.     @Override
  251.     public IntVariance combine(IntVariance other) {
  252.         sumSq.add(other.sumSq);
  253.         sum.add(other.sum);
  254.         n += other.n;
  255.         return this;
  256.     }

  257.     /**
  258.      * Sets the value of the biased flag. The default value is {@code false}.
  259.      *
  260.      * <p>If {@code false} the sum of squared deviations from the sample mean is normalised by
  261.      * {@code n - 1} where {@code n} is the number of samples. This is Bessel's correction
  262.      * for an unbiased estimator of the variance of a hypothetical infinite population.
  263.      *
  264.      * <p>If {@code true} the sum of squared deviations is normalised by the number of samples
  265.      * {@code n}.
  266.      *
  267.      * <p>Note: This option only applies when {@code n > 1}. The variance of {@code n = 1} is
  268.      * always 0.
  269.      *
  270.      * <p>This flag only controls the final computation of the statistic. The value of this flag
  271.      * will not affect compatibility between instances during a {@link #combine(IntVariance) combine}
  272.      * operation.
  273.      *
  274.      * @param v Value.
  275.      * @return {@code this} instance
  276.      */
  277.     public IntVariance setBiased(boolean v) {
  278.         biased = v;
  279.         return this;
  280.     }
  281. }