IntStandardDeviation.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 implementation uses the
  20.  * 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 zero if there is one value in the data set.
  29.  * </ul>
  30.  *
  31.  * <p>The use of the term \( n − 1 \) is called Bessel's correction. Omitting the square root,
  32.  * this provides an unbiased estimator of the variance of a hypothetical infinite population. If the
  33.  * {@link #setBiased(boolean) biased} option is enabled the normalisation factor is
  34.  * changed to \( \frac{1}{n} \) for a biased estimator of the <em>sample variance</em>.
  35.  * Note however that square root is a concave function and thus introduces negative bias
  36.  * (by Jensen's inequality), which depends on the distribution, and thus the corrected sample
  37.  * standard deviation (using Bessel's correction) is less biased, but still biased.
  38.  *
  39.  * <p>The implementation uses an exact integer sum to compute the scaled (by \( n \))
  40.  * sum of squared deviations from the mean; this is normalised by the scaled correction factor.
  41.  *
  42.  * <p>\[ \frac {n \times \sum_{i=1}^n x_i^2 - (\sum_{i=1}^n x_i)^2}{n \times (n - 1)} \]
  43.  *
  44.  * <p>Supports up to 2<sup>63</sup> (exclusive) observations.
  45.  * This implementation does not check for overflow of the count.
  46.  *
  47.  * <p>This class is designed to work with (though does not require)
  48.  * {@linkplain java.util.stream streams}.
  49.  *
  50.  * <p><strong>This implementation is not thread safe.</strong>
  51.  * If multiple threads access an instance of this class concurrently,
  52.  * and at least one of the threads invokes the {@link java.util.function.IntConsumer#accept(int) accept} or
  53.  * {@link StatisticAccumulator#combine(StatisticResult) combine} method, it must be synchronized externally.
  54.  *
  55.  * <p>However, it is safe to use {@link java.util.function.IntConsumer#accept(int) accept}
  56.  * and {@link StatisticAccumulator#combine(StatisticResult) combine}
  57.  * as {@code accumulator} and {@code combiner} functions of
  58.  * {@link java.util.stream.Collector Collector} on a parallel stream,
  59.  * because the parallel implementation of {@link java.util.stream.Stream#collect Stream.collect()}
  60.  * provides the necessary partitioning, isolation, and merging of results for
  61.  * safe and efficient parallel execution.
  62.  *
  63.  * @see <a href="https://en.wikipedia.org/wiki/Standard_deviation">Standard deviation (Wikipedia)</a>
  64.  * @see <a href="https://en.wikipedia.org/wiki/Bessel%27s_correction">Bessel&#39;s correction</a>
  65.  * @see <a href="https://en.wikipedia.org/wiki/Jensen%27s_inequality">Jensen&#39;s inequality</a>
  66.  * @see IntVariance
  67.  * @since 1.1
  68.  */
  69. public final class IntStandardDeviation implements IntStatistic, StatisticAccumulator<IntStandardDeviation> {

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

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

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

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

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

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

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

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

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

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

  164.     @Override
  165.     public IntStandardDeviation combine(IntStandardDeviation other) {
  166.         sumSq.add(other.sumSq);
  167.         sum.add(other.sum);
  168.         n += other.n;
  169.         return this;
  170.     }

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