StandardDeviation.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 standard deviation of the available values. The default implementations uses
  20.  * the following definition of the <em>sample standard deviation</em>:
  21.  *
  22.  * <p>\[ \sqrt{ \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. Omitting the square root,
  34.  * this provides an unbiased 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.  * Note however that square root is a concave function and thus introduces negative bias
  38.  * (by Jensen's inequality), which depends on the distribution, and thus the corrected sample
  39.  * standard deviation (using Bessel's correction) is less biased, but still biased.
  40.  *
  41.  * <p>The {@link #accept(double)} method uses a recursive updating algorithm based on West's
  42.  * algorithm (see Chan and Lewis (1979)).
  43.  *
  44.  * <p>The {@link #of(double...)} method uses the corrected two-pass algorithm from
  45.  * Chan <i>et al</i>, (1983).
  46.  *
  47.  * <p>Note that adding values using {@link #accept(double) accept} and then executing
  48.  * {@link #getAsDouble() getAsDouble} will
  49.  * sometimes give a different, less accurate, result than executing
  50.  * {@link #of(double...) of} with the full array of values. The former approach
  51.  * should only be used when the full array of values is not available.
  52.  *
  53.  * <p>Supports up to 2<sup>63</sup> (exclusive) observations.
  54.  * This implementation does not check for overflow of the count.
  55.  *
  56.  * <p>This class is designed to work with (though does not require)
  57.  * {@linkplain java.util.stream streams}.
  58.  *
  59.  * <p><strong>Note that this instance is not synchronized.</strong> If
  60.  * multiple threads access an instance of this class concurrently, and at least
  61.  * one of the threads invokes the {@link java.util.function.DoubleConsumer#accept(double) accept} or
  62.  * {@link StatisticAccumulator#combine(StatisticResult) combine} method, it must be synchronized externally.
  63.  *
  64.  * <p>However, it is safe to use {@link java.util.function.DoubleConsumer#accept(double) accept}
  65.  * and {@link StatisticAccumulator#combine(StatisticResult) combine}
  66.  * as {@code accumulator} and {@code combiner} functions of
  67.  * {@link java.util.stream.Collector Collector} on a parallel stream,
  68.  * because the parallel instance of {@link java.util.stream.Stream#collect Stream.collect()}
  69.  * provides the necessary partitioning, isolation, and merging of results for
  70.  * safe and efficient parallel execution.
  71.  *
  72.  * <p>References:
  73.  * <ul>
  74.  *   <li>Chan and Lewis (1979)
  75.  *       Computing standard deviations: accuracy.
  76.  *       Communications of the ACM, 22, 526-531.
  77.  *       <a href="http://doi.acm.org/10.1145/359146.359152">doi: 10.1145/359146.359152</a>
  78.  *   <li>Chan, Golub and Levesque (1983)
  79.  *       Algorithms for Computing the Sample Variance: Analysis and Recommendations.
  80.  *       American Statistician, 37, 242-247.
  81.  *       <a href="https://doi.org/10.2307/2683386">doi: 10.2307/2683386</a>
  82.  * </ul>
  83.  *
  84.  * @see <a href="https://en.wikipedia.org/wiki/Standard_deviation">Standard deviation (Wikipedia)</a>
  85.  * @see <a href="https://en.wikipedia.org/wiki/Bessel%27s_correction">Bessel&#39;s correction</a>
  86.  * @see <a href="https://en.wikipedia.org/wiki/Jensen%27s_inequality">Jensen&#39;s inequality</a>
  87.  * @see Variance
  88.  * @since 1.1
  89.  */
  90. public final class StandardDeviation implements DoubleStatistic, StatisticAccumulator<StandardDeviation> {

  91.     /**
  92.      * An instance of {@link SumOfSquaredDeviations}, which is used to
  93.      * compute the standard deviation.
  94.      */
  95.     private final SumOfSquaredDeviations ss;

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

  98.     /**
  99.      * Create an instance.
  100.      */
  101.     private StandardDeviation() {
  102.         this(new SumOfSquaredDeviations());
  103.     }

  104.     /**
  105.      * Creates an instance with the sum of squared deviations from the mean.
  106.      *
  107.      * @param ss Sum of squared deviations.
  108.      */
  109.     StandardDeviation(SumOfSquaredDeviations ss) {
  110.         this.ss = ss;
  111.     }

  112.     /**
  113.      * Creates an instance.
  114.      *
  115.      * <p>The initial result is {@code NaN}.
  116.      *
  117.      * @return {@code StandardDeviation} instance.
  118.      */
  119.     public static StandardDeviation create() {
  120.         return new StandardDeviation();
  121.     }

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

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

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

  168.     @Override
  169.     public StandardDeviation combine(StandardDeviation other) {
  170.         ss.combine(other.ss);
  171.         return this;
  172.     }

  173.     /**
  174.      * Sets the value of the biased flag. The default value is {@code false}. The bias
  175.      * term refers to the computation of the variance; the standard deviation is returned
  176.      * as the square root of the biased or unbiased <em>sample variance</em>. For further
  177.      * details see {@link Variance#setBiased(boolean) Variance.setBiased}.
  178.      *
  179.      * <p>This flag only controls the final computation of the statistic. The value of
  180.      * this flag will not affect compatibility between instances during a
  181.      * {@link #combine(StandardDeviation) combine} operation.
  182.      *
  183.      * @param v Value.
  184.      * @return {@code this} instance
  185.      * @see Variance#setBiased(boolean)
  186.      */
  187.     public StandardDeviation setBiased(boolean v) {
  188.         biased = v;
  189.         return this;
  190.     }
  191. }