You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by ah...@apache.org on 2023/09/26 16:24:17 UTC

[commons-statistics] 01/03: Refactor two-pass algorithm to FirstMoment

This is an automated email from the ASF dual-hosted git repository.

aherbert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-statistics.git

commit 0443768c4b10b92b2060d9cbbe632a7bd3833d0f
Author: Alex Herbert <ah...@apache.org>
AuthorDate: Tue Sep 26 16:17:31 2023 +0100

    Refactor two-pass algorithm to FirstMoment
---
 .../statistics/descriptive/FirstMoment.java        | 71 ++++++++++++++++------
 .../commons/statistics/descriptive/Mean.java       | 54 ++--------------
 .../commons/statistics/descriptive/Statistics.java |  3 +-
 .../commons/statistics/descriptive/Variance.java   |  2 +-
 4 files changed, 63 insertions(+), 67 deletions(-)

diff --git a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/FirstMoment.java b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/FirstMoment.java
index d9ee25e..2c354c6 100644
--- a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/FirstMoment.java
+++ b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/FirstMoment.java
@@ -47,6 +47,16 @@ import java.util.function.DoubleConsumer;
  * because the parallel implementation of {@link java.util.stream.Stream#collect Stream.collect()}
  * provides the necessary partitioning, isolation, and merging of results for
  * safe and efficient parallel execution.
+ *
+ * <p>References:
+ * <ul>
+ *   <li>Chan, Golub, Levesque (1983)
+ *       Algorithms for Computing the Sample Variance.
+ *       American Statistician, vol. 37, no. 3, pp. 242-247.
+ *   <li>Ling (1974)
+ *       Comparison of Several Algorithms for Computing Sample Means and Variances.
+ *       Journal of the American Statistical Association, Vol. 69, No. 348, pp. 859-866.
+ * </ul>
  */
 class FirstMoment implements DoubleConsumer {
     /** Count of values that have been added. */
@@ -76,30 +86,65 @@ class FirstMoment implements DoubleConsumer {
     private double nonFiniteValue;
 
     /**
-     * Create a FirstMoment instance.
+     * Create an instance.
      */
     FirstMoment() {
         // No-op
     }
 
     /**
-     * Create a FirstMoment instance with the given first moment and number of values.
+     * Create an instance with the given first moment.
+     *
      * @param m1 First moment.
      * @param n Number of values.
-     * @param nonFiniteValue Running sum of values seen so far (Used as a return value for first moment when it is non-finite).
+     * @param nonFiniteValue Running sum of values seen so far.
      */
-    FirstMoment(final double m1, final long n, final double nonFiniteValue) {
+    FirstMoment(double m1, long n, double nonFiniteValue) {
         this.m1 = m1;
         this.n = n;
         this.nonFiniteValue = nonFiniteValue;
     }
 
+    /**
+     * Returns a {@code FirstMoment} instance that has the arithmetic mean of all input
+     * values, or {@code NaN} if the input array is empty.
+     *
+     * <p>Note: {@code FirstMoment} computed using {@link FirstMoment#accept
+     * FirstMoment.accept()} may be different from this instance.
+     *
+     * @param values Values.
+     * @return {@code FirstMoment} instance.
+     */
+    static FirstMoment of(double... values) {
+        // "Corrected two-pass algorithm"
+
+        // First pass
+        final FirstMoment m1 = Statistics.add(new FirstMoment(), values);
+        final double xbar = m1.getFirstMoment();
+        if (!Double.isFinite(xbar)) {
+            return m1;
+        }
+        // Second pass
+        double correction = 0;
+        for (final double x : values) {
+            correction += x - xbar;
+        }
+        // Note: Correction may be infinite
+        correction = Double.isFinite(correction) ? correction : 0;
+        return new FirstMoment(xbar + (correction / values.length), m1.n, m1.nonFiniteValue);
+    }
+
     /**
      * Updates the state of the statistic to reflect the addition of {@code value}.
+     *
      * @param value Value.
      */
     @Override
     public void accept(double value) {
+        // "Updating one-pass algorithm"
+        // See: Chan et al (1983) Equation 1.3a
+        // This is modified with scaling to avoid overflow for all finite input.
+
         n++;
         nonFiniteValue += value;
         // To prevent overflow, dev is computed by scaling down and then scaling up.
@@ -117,11 +162,11 @@ class FirstMoment implements DoubleConsumer {
      *
      * <p>When no values have been added, the result is {@code NaN}.
      *
-     * @return {@code First moment} of all values seen so far, if it is finite.
-     * <p> {@code Infinity}, if infinities of the same sign have been encountered.
-     * <p> {@code NaN} otherwise.
+     * @return {@code First moment} of all values seen so far, if it is finite;
+     *         {@code +/-Infinity}, if infinities of the same sign have been encountered;
+     *         {@code NaN} otherwise.
      */
-    public double getFirstMoment() {
+    double getFirstMoment() {
         if (Double.isFinite(m1)) {
             return n == 0 ? Double.NaN : m1;
         }
@@ -135,7 +180,7 @@ class FirstMoment implements DoubleConsumer {
      * @param other Another {@code FirstMoment} to be combined.
      * @return {@code this} instance after combining {@code other}.
      */
-    public FirstMoment combine(FirstMoment other) {
+    FirstMoment combine(FirstMoment other) {
         if (n == 0) {
             n = other.n;
             nonFiniteValue = other.nonFiniteValue;
@@ -158,12 +203,4 @@ class FirstMoment implements DoubleConsumer {
         }
         return this;
     }
-
-    /**
-     * Gets the running sum of the values seen so far.
-     * @return Running Sum.
-     */
-    double getNonFiniteValue() {
-        return nonFiniteValue;
-    }
 }
diff --git a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Mean.java b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Mean.java
index ddb590b..0d0ba90 100644
--- a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Mean.java
+++ b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Mean.java
@@ -89,19 +89,7 @@ public abstract class Mean implements DoubleStatistic, DoubleStatisticAccumulato
      * @return {@code Mean} instance.
      */
     public static Mean of(double... values) {
-        final StorelessMean mean = Statistics.add(new StorelessMean(), values);
-
-        if (!Double.isFinite(mean.getAsDouble())) {
-            return mean;
-        }
-        final double xbar = mean.getAsDouble();
-        double correction = 0;
-        for (final double value : values) {
-            correction += value - xbar;
-        }
-        // Correction may be infinite
-        correction = Double.isFinite(correction) ? correction : 0;
-        return StorelessMean.create(xbar + (correction / values.length), mean.getN(), mean.getNonFiniteValue());
+        return new StorelessMean(FirstMoment.of(values));
     }
 
     /**
@@ -132,33 +120,19 @@ public abstract class Mean implements DoubleStatistic, DoubleStatisticAccumulato
         private final FirstMoment firstMoment;
 
         /**
-         * Creates a StorelessMean instance with an External Moment.
+         * Creates an instance with a moment.
          *
          * @param m1 First moment.
-         * @param n Number of values.
-         * @param nonFiniteValue Sum of values, which may be non-finite.
          */
-        private StorelessMean(final double m1, final long n, final double nonFiniteValue) {
-            firstMoment = new FirstMoment(m1, n, nonFiniteValue);
+        StorelessMean(FirstMoment m1) {
+            firstMoment = m1;
         }
 
         /**
-         * Create a Mean instance.
+         * Create an instance.
          */
         StorelessMean() {
-            firstMoment = new FirstMoment();
-        }
-
-        /**
-         * Creates a StorelessMean instance with an External Moment.
-         *
-         * @param m1 First moment.
-         * @param n Number of values.
-         * @param nonFinite Sum of values, which may be non-finite.
-         * @return A StorelessMean instance.
-         */
-        static StorelessMean create(final double m1, final long n, final double nonFinite) {
-            return new StorelessMean(m1, n, nonFinite);
+            this(new FirstMoment());
         }
 
         @Override
@@ -177,21 +151,5 @@ public abstract class Mean implements DoubleStatistic, DoubleStatisticAccumulato
             firstMoment.combine(that.firstMoment);
             return this;
         }
-
-        /**
-         * Gets the number of values that have been added.
-         * @return Number of values.
-         */
-        long getN() {
-            return firstMoment.n;
-        }
-
-        /**
-         * Gets the running sum of the values seen so far.
-         * @return Running Sum.
-         */
-        double getNonFiniteValue() {
-            return firstMoment.getNonFiniteValue();
-        }
     }
 }
diff --git a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Statistics.java b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Statistics.java
index bd5abfc..6c72e62 100644
--- a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Statistics.java
+++ b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Statistics.java
@@ -17,6 +17,7 @@
 package org.apache.commons.statistics.descriptive;
 
 import java.util.Arrays;
+import java.util.function.DoubleConsumer;
 
 /**
  * Utility methods for statistics.
@@ -34,7 +35,7 @@ final class Statistics {
      * @param values Values.
      * @return the statistic
      */
-    static <T extends DoubleStatistic> T add(T statistic, double[] values) {
+    static <T extends DoubleConsumer> T add(T statistic, double[] values) {
         Arrays.stream(values).forEach(statistic);
         return statistic;
     }
diff --git a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Variance.java b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Variance.java
index 731cde7..2f9efe8 100644
--- a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Variance.java
+++ b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Variance.java
@@ -110,7 +110,7 @@ public abstract class Variance implements DoubleStatistic, DoubleStatisticAccumu
      * @return {@code Variance} instance.
      */
     public static Variance of(double... values) {
-        final double mean = Mean.of(values).getAsDouble();
+        final double mean = FirstMoment.of(values).getFirstMoment();
         if (!Double.isFinite(mean)) {
             return StorelessSampleVariance.create(Math.abs(mean), mean, values.length, mean);
         }