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 import java.util.function.DoubleConsumer; 20 21 /** 22 * Computes the first moment (arithmetic mean) using the definitional formula: 23 * 24 * <pre>mean = sum(x_i) / n</pre> 25 * 26 * <p> To limit numeric errors, the value of the statistic is computed using the 27 * following recursive updating algorithm: 28 * <ol> 29 * <li>Initialize {@code m = } the first value</li> 30 * <li>For each additional value, update using <br> 31 * {@code m = m + (new value - m) / (number of observations)}</li> 32 * </ol> 33 * 34 * <p>Returns {@code NaN} if the dataset is empty. Note that 35 * {@code NaN} may also be returned if the input includes {@code NaN} and / or infinite 36 * values of opposite sign. 37 * 38 * <p>Supports up to 2<sup>63</sup> (exclusive) observations. 39 * This implementation does not check for overflow of the count. 40 * 41 * <p><strong>Note that this implementation is not synchronized.</strong> If 42 * multiple threads access an instance of this class concurrently, and at least 43 * one of the threads invokes the {@link java.util.function.DoubleConsumer#accept(double) accept} or 44 * {@link StatisticAccumulator#combine(StatisticResult) combine} method, it must be synchronized externally. 45 * 46 * <p>However, it is safe to use {@link java.util.function.DoubleConsumer#accept(double) accept} 47 * and {@link StatisticAccumulator#combine(StatisticResult) combine} 48 * as {@code accumulator} and {@code combiner} functions of 49 * {@link java.util.stream.Collector Collector} on a parallel stream, 50 * because the parallel implementation of {@link java.util.stream.Stream#collect Stream.collect()} 51 * provides the necessary partitioning, isolation, and merging of results for 52 * safe and efficient parallel execution. 53 * 54 * <p>References: 55 * <ul> 56 * <li>Chan, Golub, Levesque (1983) 57 * Algorithms for Computing the Sample Variance. 58 * American Statistician, vol. 37, no. 3, pp. 242-247. 59 * <li>Ling (1974) 60 * Comparison of Several Algorithms for Computing Sample Means and Variances. 61 * Journal of the American Statistical Association, Vol. 69, No. 348, pp. 859-866. 62 * </ul> 63 * 64 * @since 1.1 65 */ 66 class FirstMoment implements DoubleConsumer { 67 /** The downscale constant. Used to avoid overflow for all finite input. */ 68 private static final double DOWNSCALE = 0.5; 69 /** The rescale constant. */ 70 private static final double RESCALE = 2; 71 72 /** Count of values that have been added. */ 73 protected long n; 74 75 /** 76 * Half the deviation of most recently added value from the previous first moment. 77 * Retained to prevent repeated computation in higher order moments. 78 * 79 * <p>Note: This is (x - m1) / 2. It is computed as a half value to prevent overflow 80 * when computing for any finite value x and m. 81 * 82 * <p>This value is not used in the {@link #combine(FirstMoment)} method. 83 */ 84 protected double dev; 85 86 /** 87 * Half the deviation of most recently added value from the previous first moment, 88 * normalized by current sample size. Retained to prevent repeated 89 * computation in higher order moments. 90 * 91 * <p>Note: This is (x - m1) / 2n. It is computed as a half value to prevent overflow 92 * when computing for any finite value x and m. 93 * 94 * Note: This value is not used in the {@link #combine(FirstMoment)} method. 95 */ 96 protected double nDev; 97 98 /** First moment of values that have been added. 99 * This is stored as a half value to prevent overflow for any finite input. 100 * Benchmarks show this has negligible performance impact. */ 101 private double m1; 102 103 /** 104 * Running sum of values seen so far. 105 * This is not used in the computation of mean. Used as a return value for first moment when 106 * it is non-finite. 107 */ 108 private double nonFiniteValue; 109 110 /** 111 * Create an instance. 112 */ 113 FirstMoment() { 114 // No-op 115 } 116 117 /** 118 * Copy constructor. 119 * 120 * @param source Source to copy. 121 */ 122 FirstMoment(FirstMoment source) { 123 m1 = source.m1; 124 n = source.n; 125 nonFiniteValue = source.nonFiniteValue; 126 } 127 128 /** 129 * Create an instance with the given first moment. 130 * 131 * <p>This constructor is used when creating the moment from a finite sum of values. 132 * 133 * @param m1 First moment. 134 * @param n Count of values. 135 */ 136 FirstMoment(double m1, long n) { 137 this.m1 = m1 * DOWNSCALE; 138 this.n = n; 139 } 140 141 /** 142 * Returns an instance populated using the input {@code values}. 143 * 144 * <p>Note: {@code FirstMoment} computed using {@link #accept} may be different from 145 * this instance. 146 * 147 * @param values Values. 148 * @return {@code FirstMoment} instance. 149 */ 150 static FirstMoment of(double... values) { 151 if (values.length == 0) { 152 return new FirstMoment(); 153 } 154 // In the typical use-case a sum of values will not overflow and 155 // is faster than the rolling algorithm 156 return create(org.apache.commons.numbers.core.Sum.of(values), values); 157 } 158 159 /** 160 * Creates the first moment. 161 * 162 * <p>Uses the provided {@code sum} if finite; otherwise reverts to using the rolling moment 163 * to protect from overflow and adds a second pass correction term. 164 * 165 * <p>This method is used by {@link DoubleStatistics} using a sum that can be reused 166 * for the {@link Sum} statistic. 167 * 168 * @param sum Sum of the values. 169 * @param values Values. 170 * @return {@code FirstMoment} instance. 171 */ 172 static FirstMoment create(org.apache.commons.numbers.core.Sum sum, double[] values) { 173 // Protect against empty values 174 if (values.length == 0) { 175 return new FirstMoment(); 176 } 177 178 final double s = sum.getAsDouble(); 179 if (Double.isFinite(s)) { 180 return new FirstMoment(s / values.length, values.length); 181 } 182 183 // "Corrected two-pass algorithm" 184 185 // First pass 186 final FirstMoment m1 = create(values); 187 final double xbar = m1.getFirstMoment(); 188 if (!Double.isFinite(xbar)) { 189 return m1; 190 } 191 // Second pass 192 double correction = 0; 193 for (final double x : values) { 194 correction += x - xbar; 195 } 196 // Note: Correction may be infinite 197 if (Double.isFinite(correction)) { 198 // Down scale the correction to the half representation 199 m1.m1 += DOWNSCALE * correction / values.length; 200 } 201 return m1; 202 } 203 204 /** 205 * Creates the first moment using a rolling algorithm. 206 * 207 * <p>This duplicates the algorithm in the {@link #accept(double)} method 208 * with optimisations due to the processing of an entire array: 209 * <ul> 210 * <li>Avoid updating (unused) class level working variables. 211 * <li>Only computing the non-finite value if required. 212 * </ul> 213 * 214 * @param values Values. 215 * @return the first moment 216 */ 217 private static FirstMoment create(double[] values) { 218 double m1 = 0; 219 int n = 0; 220 for (final double x : values) { 221 // Downscale to avoid overflow for all finite input 222 m1 += (x * DOWNSCALE - m1) / ++n; 223 } 224 final FirstMoment m = new FirstMoment(); 225 m.n = n; 226 // Note: m1 is already downscaled here 227 m.m1 = m1; 228 // The non-finite value is only relevant if the data contains inf/nan 229 if (!Double.isFinite(m1 * RESCALE)) { 230 m.nonFiniteValue = computeNonFiniteValue(values); 231 } 232 return m; 233 } 234 235 /** 236 * Compute the result in the event of non-finite values. 237 * 238 * @param values Values. 239 * @return the non-finite result 240 */ 241 private static double computeNonFiniteValue(double[] values) { 242 double sum = 0; 243 for (final double x : values) { 244 // Scaling down values prevents overflow of finites. 245 sum += x * Double.MIN_NORMAL; 246 } 247 return sum; 248 } 249 250 /** 251 * Updates the state of the statistic to reflect the addition of {@code value}. 252 * 253 * @param value Value. 254 */ 255 @Override 256 public void accept(double value) { 257 // "Updating one-pass algorithm" 258 // See: Chan et al (1983) Equation 1.3a 259 // m_{i+1} = m_i + (x - m_i) / (i + 1) 260 // This is modified with scaling to avoid overflow for all finite input. 261 // Scaling the input down by a factor of two ensures that the scaling is lossless. 262 // Sub-classes must alter their scaling factors when using the computed deviations. 263 264 // Note: Maintain the correct non-finite result. 265 // Scaling down values prevents overflow of finites. 266 nonFiniteValue += value * Double.MIN_NORMAL; 267 // Scale down the input 268 dev = value * DOWNSCALE - m1; 269 nDev = dev / ++n; 270 m1 += nDev; 271 } 272 273 /** 274 * Gets the first moment of all input values. 275 * 276 * <p>When no values have been added, the result is {@code NaN}. 277 * 278 * @return {@code First moment} of all values, if it is finite; 279 * {@code +/-Infinity}, if infinities of the same sign have been encountered; 280 * {@code NaN} otherwise. 281 */ 282 double getFirstMoment() { 283 // Scale back to the original magnitude 284 final double m = m1 * RESCALE; 285 if (Double.isFinite(m)) { 286 return n == 0 ? Double.NaN : m; 287 } 288 // A non-finite value must have been encountered, return nonFiniteValue which represents m1. 289 return nonFiniteValue; 290 } 291 292 /** 293 * Combines the state of another {@code FirstMoment} into this one. 294 * 295 * @param other Another {@code FirstMoment} to be combined. 296 * @return {@code this} instance after combining {@code other}. 297 */ 298 FirstMoment combine(FirstMoment other) { 299 nonFiniteValue += other.nonFiniteValue; 300 final double mu1 = this.m1; 301 final double mu2 = other.m1; 302 final long n1 = n; 303 final long n2 = other.n; 304 n = n1 + n2; 305 // Adjust the mean with the weighted difference: 306 // m1 = m1 + (m2 - m1) * n2 / (n1 + n2) 307 // The half-representation ensures the difference of means is at most MAX_VALUE 308 // so the combine can avoid scaling. 309 if (n1 == n2) { 310 // Optimisation for equal sizes: m1 = (m1 + m2) / 2 311 m1 = (mu1 + mu2) * 0.5; 312 } else { 313 m1 = combine(mu1, mu2, n1, n2); 314 } 315 return this; 316 } 317 318 /** 319 * Combine the moments. This method is used to enforce symmetry. It assumes that 320 * the two sizes are not identical, and at least one size is non-zero. 321 * 322 * @param m1 Moment 1. 323 * @param m2 Moment 2. 324 * @param n1 Size of sample 1. 325 * @param n2 Size of sample 2. 326 * @return the combined first moment 327 */ 328 private static double combine(double m1, double m2, long n1, long n2) { 329 // Note: If either size is zero the weighted difference is zero and 330 // the other moment is unchanged. 331 return n2 < n1 ? 332 m1 + (m2 - m1) * ((double) n2 / (n1 + n2)) : 333 m2 + (m1 - m2) * ((double) n1 / (n1 + n2)); 334 } 335 336 /** 337 * Gets the difference of the first moment between {@code this} moment and the 338 * {@code other} moment. This is provided for sub-classes. 339 * 340 * @param other Other moment. 341 * @return the difference 342 */ 343 double getFirstMomentDifference(FirstMoment other) { 344 // Scale back to the original magnitude 345 return (m1 - other.m1) * RESCALE; 346 } 347 348 /** 349 * Gets the half the difference of the first moment between {@code this} moment and 350 * the {@code other} moment. This is provided for sub-classes. 351 * 352 * @param other Other moment. 353 * @return the difference 354 */ 355 double getFirstMomentHalfDifference(FirstMoment other) { 356 return m1 - other.m1; 357 } 358 }