Variance.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 variance of the available values. The default implementation uses the
  20.  * following definition of the <em>sample variance</em>:
  21.  *
  22.  * <p>\[ \tfrac{1}{n-1} \sum_{i=1}^n (x_i-\overline{x})^2 \]
  23.  *
  24.  * <p>where \( \overline{x} \) is the sample mean, and \( n \) is the number of samples.
  25.  *
  26.  * <ul>
  27.  *   <li>The result is {@code NaN} if no values are added.
  28.  *   <li>The result is {@code NaN} if any of the values is {@code NaN} or infinite.
  29.  *   <li>The result is {@code NaN} if the sum of the squared deviations from the mean is infinite.
  30.  *   <li>The result is zero if there is one finite value in the data set.
  31.  * </ul>
  32.  *
  33.  * <p>The use of the term \( n − 1 \) is called Bessel's correction. This is an unbiased
  34.  * estimator of the variance of a hypothetical infinite population. If the
  35.  * {@link #setBiased(boolean) biased} option is enabled the normalisation factor is
  36.  * changed to \( \frac{1}{n} \) for a biased estimator of the <em>sample variance</em>.
  37.  *
  38.  * <p>The {@link #accept(double)} method uses a recursive updating algorithm based on West's
  39.  * algorithm (see Chan and Lewis (1979)).
  40.  *
  41.  * <p>The {@link #of(double...)} method uses the corrected two-pass algorithm from
  42.  * Chan <i>et al</i>, (1983).
  43.  *
  44.  * <p>Note that adding values using {@link #accept(double) accept} and then executing
  45.  * {@link #getAsDouble() getAsDouble} will
  46.  * sometimes give a different, less accurate, result than executing
  47.  * {@link #of(double...) of} with the full array of values. The former approach
  48.  * should only be used when the full array of values is not available.
  49.  *
  50.  * <p>Supports up to 2<sup>63</sup> (exclusive) observations.
  51.  * This implementation does not check for overflow of the count.
  52.  *
  53.  * <p>This class is designed to work with (though does not require)
  54.  * {@linkplain java.util.stream streams}.
  55.  *
  56.  * <p><strong>Note that this instance is not synchronized.</strong> If
  57.  * multiple threads access an instance of this class concurrently, and at least
  58.  * one of the threads invokes the {@link java.util.function.DoubleConsumer#accept(double) accept} or
  59.  * {@link StatisticAccumulator#combine(StatisticResult) combine} method, it must be synchronized externally.
  60.  *
  61.  * <p>However, it is safe to use {@link java.util.function.DoubleConsumer#accept(double) accept}
  62.  * and {@link StatisticAccumulator#combine(StatisticResult) combine}
  63.  * as {@code accumulator} and {@code combiner} functions of
  64.  * {@link java.util.stream.Collector Collector} on a parallel stream,
  65.  * because the parallel instance of {@link java.util.stream.Stream#collect Stream.collect()}
  66.  * provides the necessary partitioning, isolation, and merging of results for
  67.  * safe and efficient parallel execution.
  68.  *
  69.  * <p>References:
  70.  * <ul>
  71.  *   <li>Chan and Lewis (1979)
  72.  *       Computing standard deviations: accuracy.
  73.  *       Communications of the ACM, 22, 526-531.
  74.  *       <a href="http://doi.acm.org/10.1145/359146.359152">doi: 10.1145/359146.359152</a>
  75.  *   <li>Chan, Golub and Levesque (1983)
  76.  *       Algorithms for Computing the Sample Variance: Analysis and Recommendations.
  77.  *       American Statistician, 37, 242-247.
  78.  *       <a href="https://doi.org/10.2307/2683386">doi: 10.2307/2683386</a>
  79.  * </ul>
  80.  *
  81.  * @see <a href="https://en.wikipedia.org/wiki/Variance">Variance (Wikipedia)</a>
  82.  * @see <a href="https://en.wikipedia.org/wiki/Bessel%27s_correction">Bessel&#39;s correction</a>
  83.  * @see StandardDeviation
  84.  * @since 1.1
  85.  */
  86. public final class Variance implements DoubleStatistic, StatisticAccumulator<Variance> {

  87.     /**
  88.      * An instance of {@link SumOfSquaredDeviations}, which is used to
  89.      * compute the variance.
  90.      */
  91.     private final SumOfSquaredDeviations ss;

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

  94.     /**
  95.      * Create an instance.
  96.      */
  97.     private Variance() {
  98.         this(new SumOfSquaredDeviations());
  99.     }

  100.     /**
  101.      * Creates an instance with the sum of squared deviations from the mean.
  102.      *
  103.      * @param ss Sum of squared deviations.
  104.      */
  105.     Variance(SumOfSquaredDeviations ss) {
  106.         this.ss = ss;
  107.     }

  108.     /**
  109.      * Creates an instance.
  110.      *
  111.      * <p>The initial result is {@code NaN}.
  112.      *
  113.      * @return {@code Variance} instance.
  114.      */
  115.     public static Variance create() {
  116.         return new Variance();
  117.     }

  118.     /**
  119.      * Returns an instance populated using the input {@code values}.
  120.      *
  121.      * <p>Note: {@code Variance} computed using {@link #accept(double) accept} may be
  122.      * different from this variance.
  123.      *
  124.      * <p>See {@link Variance} for details on the computing algorithm.
  125.      *
  126.      * @param values Values.
  127.      * @return {@code Variance} instance.
  128.      */
  129.     public static Variance of(double... values) {
  130.         return new Variance(SumOfSquaredDeviations.of(values));
  131.     }

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

  141.     /**
  142.      * Gets the variance of all input values.
  143.      *
  144.      * <p>When no values have been added, the result is {@code NaN}.
  145.      *
  146.      * @return variance of all values.
  147.      */
  148.     @Override
  149.     public double getAsDouble() {
  150.         // This method checks the sum of squared is finite
  151.         // to provide a consistent NaN when the computation is not possible.
  152.         // Note: The SS checks for n=0 and returns NaN.
  153.         final double m2 = ss.getSumOfSquaredDeviations();
  154.         if (!Double.isFinite(m2)) {
  155.             return Double.NaN;
  156.         }
  157.         final long n = ss.n;
  158.         // Avoid a divide by zero
  159.         if (n == 1) {
  160.             return 0;
  161.         }
  162.         return biased ? m2 / n : m2 / (n - 1);
  163.     }

  164.     @Override
  165.     public Variance combine(Variance other) {
  166.         ss.combine(other.ss);
  167.         return this;
  168.     }

  169.     /**
  170.      * Sets the value of the biased flag. The default value is {@code false}.
  171.      *
  172.      * <p>If {@code false} the sum of squared deviations from the sample mean is normalised by
  173.      * {@code n - 1} where {@code n} is the number of samples. This is Bessel's correction
  174.      * for an unbiased estimator of the variance of a hypothetical infinite population.
  175.      *
  176.      * <p>If {@code true} the sum of squared deviations is normalised by the number of samples
  177.      * {@code n}.
  178.      *
  179.      * <p>Note: This option only applies when {@code n > 1}. The variance of {@code n = 1} is
  180.      * always 0.
  181.      *
  182.      * <p>This flag only controls the final computation of the statistic. The value of this flag
  183.      * will not affect compatibility between instances during a {@link #combine(Variance) combine}
  184.      * operation.
  185.      *
  186.      * @param v Value.
  187.      * @return {@code this} instance
  188.      */
  189.     public Variance setBiased(boolean v) {
  190.         biased = v;
  191.         return this;
  192.     }
  193. }