1 /*
   2  * Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 package java.util;
  26 
  27 import java.util.function.DoubleConsumer;
  28 import java.util.stream.Collector;
  29 import java.util.stream.DoubleStream;
  30 
  31 /**
  32  * A state object for collecting statistics such as count, min, max, sum, and
  33  * average.
  34  *
  35  * <p>This class is designed to work with (though does not require)
  36  * {@linkplain java.util.stream streams}. For example, you can compute
  37  * summary statistics on a stream of doubles with:
  38  * <pre> {@code
  39  * DoubleSummaryStatistics stats = doubleStream.collect(DoubleSummaryStatistics::new,
  40  *                                                      DoubleSummaryStatistics::accept,
  41  *                                                      DoubleSummaryStatistics::combine);
  42  * }</pre>
  43  *
  44  * <p>{@code DoubleSummaryStatistics} can be used as a
  45  * {@linkplain java.util.stream.Stream#collect(Collector) reduction}
  46  * target for a {@linkplain java.util.stream.Stream stream}. For example:
  47  *
  48  * <pre> {@code
  49  * DoubleSummaryStatistics stats = people.stream()
  50  *     .collect(Collectors.summarizingDouble(Person::getWeight));
  51  *}</pre>
  52  *
  53  * This computes, in a single pass, the count of people, as well as the minimum,
  54  * maximum, sum, and average of their weights.
  55  *
  56  * @implNote This implementation is not thread safe. However, it is safe to use
  57  * {@link java.util.stream.Collectors#summarizingDouble(java.util.function.ToDoubleFunction)
  58  * Collectors.summarizingDouble()} on a parallel stream, because the parallel
  59  * 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  * <p>This implementation does not check for overflow of the count.
  64  * @since 1.8
  65  */
  66 public class DoubleSummaryStatistics implements DoubleConsumer {
  67     private long count;
  68     private double sum;
  69     private double sumCompensation; // Low order bits of sum
  70     private double simpleSum; // Used to compute right sum for non-finite inputs
  71     private double min = Double.POSITIVE_INFINITY;
  72     private double max = Double.NEGATIVE_INFINITY;
  73 
  74     /**
  75      * Constructs an empty instance with zero count, zero sum,
  76      * {@code Double.POSITIVE_INFINITY} min, {@code Double.NEGATIVE_INFINITY}
  77      * max and zero average.
  78      */
  79     public DoubleSummaryStatistics() { }
  80 
  81     /**
  82      * Constructs a non-empty instance with the specified {@code count},
  83      * {@code min}, {@code max}, and {@code sum}.
  84      *
  85      * <p>If {@code count} is zero then the remaining arguments are ignored and
  86      * an empty instance is constructed.
  87      *
  88      * <p>If the arguments are inconsistent then an {@code IllegalArgumentException}
  89      * is thrown.  The necessary consistent argument conditions are:
  90      * <ul>
  91      *   <li>{@code count >= 0}</li>
  92      *   <li>{@code (min <= max && !isNaN(sum)) || (isNaN(min) && isNaN(max) && isNaN(sum))}</li>
  93      * </ul>
  94      * @apiNote
  95      * The enforcement of argument correctness means that the retrieved set of
  96      * recorded values obtained from a {@code DoubleSummaryStatistics} source
  97      * instance may not be a legal set of arguments for this constructor due to
  98      * arithmetic overflow of the source's recorded count of values.
  99      * The consistent argument conditions are not sufficient to prevent the
 100      * creation of an internally inconsistent instance.  An example of such a
 101      * state would be an instance with: {@code count} = 2, {@code min} = 1,
 102      * {@code max} = 2, and {@code sum} = 0.
 103      *
 104      * @param count the count of values
 105      * @param min the minimum value
 106      * @param max the maximum value
 107      * @param sum the sum of all values
 108      * @throws IllegalArgumentException if the arguments are inconsistent
 109      * @since 10
 110      */
 111     public DoubleSummaryStatistics(long count, double min, double max, double sum)
 112             throws IllegalArgumentException {
 113         if (count < 0L) {
 114             throw new IllegalArgumentException("Negative count value");
 115         } else if (count > 0L) {
 116             if (min > max)
 117                 throw new IllegalArgumentException("Minimum greater than maximum");
 118 
 119             // All NaN or non NaN
 120             var ncount = DoubleStream.of(min, max, sum).filter(Double::isNaN).count();
 121             if (ncount > 0 && ncount < 3)
 122                 throw new IllegalArgumentException("Some, not all, of the minimum, maximum, or sum is NaN");
 123 
 124             this.count = count;
 125             this.sum = sum;
 126             this.simpleSum = sum;
 127             this.sumCompensation = 0.0d;
 128             this.min = min;
 129             this.max = max;
 130         }
 131         // Use default field values if count == 0
 132     }
 133 
 134     /**
 135      * Records another value into the summary information.
 136      *
 137      * @param value the input value
 138      */
 139     @Override
 140     public void accept(double value) {
 141         ++count;
 142         simpleSum += value;
 143         sumWithCompensation(value);
 144         min = Math.min(min, value);
 145         max = Math.max(max, value);
 146     }
 147 
 148     /**
 149      * Combines the state of another {@code DoubleSummaryStatistics} into this
 150      * one.
 151      *
 152      * @param other another {@code DoubleSummaryStatistics}
 153      * @throws NullPointerException if {@code other} is null
 154      */
 155     public void combine(DoubleSummaryStatistics other) {
 156         count += other.count;
 157         simpleSum += other.simpleSum;
 158         sumWithCompensation(other.sum);
 159         sumWithCompensation(other.sumCompensation);
 160         min = Math.min(min, other.min);
 161         max = Math.max(max, other.max);
 162     }
 163 
 164     /**
 165      * Incorporate a new double value using Kahan summation /
 166      * compensated summation.
 167      */
 168     private void sumWithCompensation(double value) {
 169         double tmp = value - sumCompensation;
 170         double velvel = sum + tmp; // Little wolf of rounding error
 171         sumCompensation = (velvel - sum) - tmp;
 172         sum = velvel;
 173     }
 174 
 175     /**
 176      * Return the count of values recorded.
 177      *
 178      * @return the count of values
 179      */
 180     public final long getCount() {
 181         return count;
 182     }
 183 
 184     /**
 185      * Returns the sum of values recorded, or zero if no values have been
 186      * recorded.
 187      *
 188      * <p> The value of a floating-point sum is a function both of the
 189      * input values as well as the order of addition operations. The
 190      * order of addition operations of this method is intentionally
 191      * not defined to allow for implementation flexibility to improve
 192      * the speed and accuracy of the computed result.
 193      *
 194      * In particular, this method may be implemented using compensated
 195      * summation or other technique to reduce the error bound in the
 196      * numerical sum compared to a simple summation of {@code double}
 197      * values.
 198      *
 199      * Because of the unspecified order of operations and the
 200      * possibility of using differing summation schemes, the output of
 201      * this method may vary on the same input values.
 202      *
 203      * <p>Various conditions can result in a non-finite sum being
 204      * computed. This can occur even if the all the recorded values
 205      * being summed are finite. If any recorded value is non-finite,
 206      * the sum will be non-finite:
 207      *
 208      * <ul>
 209      *
 210      * <li>If any recorded value is a NaN, then the final sum will be
 211      * NaN.
 212      *
 213      * <li>If the recorded values contain one or more infinities, the
 214      * sum will be infinite or NaN.
 215      *
 216      * <ul>
 217      *
 218      * <li>If the recorded values contain infinities of opposite sign,
 219      * the sum will be NaN.
 220      *
 221      * <li>If the recorded values contain infinities of one sign and
 222      * an intermediate sum overflows to an infinity of the opposite
 223      * sign, the sum may be NaN.
 224      *
 225      * </ul>
 226      *
 227      * </ul>
 228      *
 229      * It is possible for intermediate sums of finite values to
 230      * overflow into opposite-signed infinities; if that occurs, the
 231      * final sum will be NaN even if the recorded values are all
 232      * finite.
 233      *
 234      * If all the recorded values are zero, the sign of zero is
 235      * <em>not</em> guaranteed to be preserved in the final sum.
 236      *
 237      * @apiNote Values sorted by increasing absolute magnitude tend to yield
 238      * more accurate results.
 239      *
 240      * @return the sum of values, or zero if none
 241      */
 242     public final double getSum() {
 243         // Better error bounds to add both terms as the final sum
 244         double tmp =  sum + sumCompensation;
 245         if (Double.isNaN(tmp) && Double.isInfinite(simpleSum))
 246             // If the compensated sum is spuriously NaN from
 247             // accumulating one or more same-signed infinite values,
 248             // return the correctly-signed infinity stored in
 249             // simpleSum.
 250             return simpleSum;
 251         else
 252             return tmp;
 253     }
 254 
 255     /**
 256      * Returns the minimum recorded value, {@code Double.NaN} if any recorded
 257      * value was NaN or {@code Double.POSITIVE_INFINITY} if no values were
 258      * recorded. Unlike the numerical comparison operators, this method
 259      * considers negative zero to be strictly smaller than positive zero.
 260      *
 261      * @return the minimum recorded value, {@code Double.NaN} if any recorded
 262      * value was NaN or {@code Double.POSITIVE_INFINITY} if no values were
 263      * recorded
 264      */
 265     public final double getMin() {
 266         return min;
 267     }
 268 
 269     /**
 270      * Returns the maximum recorded value, {@code Double.NaN} if any recorded
 271      * value was NaN or {@code Double.NEGATIVE_INFINITY} if no values were
 272      * recorded. Unlike the numerical comparison operators, this method
 273      * considers negative zero to be strictly smaller than positive zero.
 274      *
 275      * @return the maximum recorded value, {@code Double.NaN} if any recorded
 276      * value was NaN or {@code Double.NEGATIVE_INFINITY} if no values were
 277      * recorded
 278      */
 279     public final double getMax() {
 280         return max;
 281     }
 282 
 283     /**
 284      * Returns the arithmetic mean of values recorded, or zero if no
 285      * values have been recorded.
 286      *
 287      * <p> The computed average can vary numerically and have the
 288      * special case behavior as computing the sum; see {@link #getSum}
 289      * for details.
 290      *
 291      * @apiNote Values sorted by increasing absolute magnitude tend to yield
 292      * more accurate results.
 293      *
 294      * @return the arithmetic mean of values, or zero if none
 295      */
 296     public final double getAverage() {
 297         return getCount() > 0 ? getSum() / getCount() : 0.0d;
 298     }
 299 
 300     /**
 301      * Returns a non-empty string representation of this object suitable for
 302      * debugging. The exact presentation format is unspecified and may vary
 303      * between implementations and versions.
 304      */
 305     @Override
 306     public String toString() {
 307         return String.format(
 308             "%s{count=%d, sum=%f, min=%f, average=%f, max=%f}",
 309             this.getClass().getSimpleName(),
 310             getCount(),
 311             getSum(),
 312             getMin(),
 313             getAverage(),
 314             getMax());
 315     }
 316 }