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      */
DoubleSummaryStatistics()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      */
DoubleSummaryStatistics(long count, double min, double max, double sum)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
accept(double value)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      */
combine(DoubleSummaryStatistics other)155     public void combine(DoubleSummaryStatistics other) {
156         count += other.count;
157         simpleSum += other.simpleSum;
158         sumWithCompensation(other.sum);
159 
160         // Subtract compensation bits
161         sumWithCompensation(-other.sumCompensation);
162         min = Math.min(min, other.min);
163         max = Math.max(max, other.max);
164     }
165 
166     /**
167      * Incorporate a new double value using Kahan summation /
168      * compensated summation.
169      */
sumWithCompensation(double value)170     private void sumWithCompensation(double value) {
171         double tmp = value - sumCompensation;
172         double velvel = sum + tmp; // Little wolf of rounding error
173         sumCompensation = (velvel - sum) - tmp;
174         sum = velvel;
175     }
176 
177     /**
178      * Return the count of values recorded.
179      *
180      * @return the count of values
181      */
getCount()182     public final long getCount() {
183         return count;
184     }
185 
186     /**
187      * Returns the sum of values recorded, or zero if no values have been
188      * recorded.
189      *
190      * <p> The value of a floating-point sum is a function both of the
191      * input values as well as the order of addition operations. The
192      * order of addition operations of this method is intentionally
193      * not defined to allow for implementation flexibility to improve
194      * the speed and accuracy of the computed result.
195      *
196      * In particular, this method may be implemented using compensated
197      * summation or other technique to reduce the error bound in the
198      * numerical sum compared to a simple summation of {@code double}
199      * values.
200      *
201      * Because of the unspecified order of operations and the
202      * possibility of using differing summation schemes, the output of
203      * this method may vary on the same input values.
204      *
205      * <p>Various conditions can result in a non-finite sum being
206      * computed. This can occur even if the all the recorded values
207      * being summed are finite. If any recorded value is non-finite,
208      * the sum will be non-finite:
209      *
210      * <ul>
211      *
212      * <li>If any recorded value is a NaN, then the final sum will be
213      * NaN.
214      *
215      * <li>If the recorded values contain one or more infinities, the
216      * sum will be infinite or NaN.
217      *
218      * <ul>
219      *
220      * <li>If the recorded values contain infinities of opposite sign,
221      * the sum will be NaN.
222      *
223      * <li>If the recorded values contain infinities of one sign and
224      * an intermediate sum overflows to an infinity of the opposite
225      * sign, the sum may be NaN.
226      *
227      * </ul>
228      *
229      * </ul>
230      *
231      * It is possible for intermediate sums of finite values to
232      * overflow into opposite-signed infinities; if that occurs, the
233      * final sum will be NaN even if the recorded values are all
234      * finite.
235      *
236      * If all the recorded values are zero, the sign of zero is
237      * <em>not</em> guaranteed to be preserved in the final sum.
238      *
239      * @apiNote Values sorted by increasing absolute magnitude tend to yield
240      * more accurate results.
241      *
242      * @return the sum of values, or zero if none
243      */
getSum()244     public final double getSum() {
245         // Better error bounds to add both terms as the final sum
246         double tmp =  sum - sumCompensation;
247         if (Double.isNaN(tmp) && Double.isInfinite(simpleSum))
248             // If the compensated sum is spuriously NaN from
249             // accumulating one or more same-signed infinite values,
250             // return the correctly-signed infinity stored in
251             // simpleSum.
252             return simpleSum;
253         else
254             return tmp;
255     }
256 
257     /**
258      * Returns the minimum recorded value, {@code Double.NaN} if any recorded
259      * value was NaN or {@code Double.POSITIVE_INFINITY} if no values were
260      * recorded. Unlike the numerical comparison operators, this method
261      * considers negative zero to be strictly smaller than positive zero.
262      *
263      * @return the minimum recorded value, {@code Double.NaN} if any recorded
264      * value was NaN or {@code Double.POSITIVE_INFINITY} if no values were
265      * recorded
266      */
getMin()267     public final double getMin() {
268         return min;
269     }
270 
271     /**
272      * Returns the maximum recorded value, {@code Double.NaN} if any recorded
273      * value was NaN or {@code Double.NEGATIVE_INFINITY} if no values were
274      * recorded. Unlike the numerical comparison operators, this method
275      * considers negative zero to be strictly smaller than positive zero.
276      *
277      * @return the maximum recorded value, {@code Double.NaN} if any recorded
278      * value was NaN or {@code Double.NEGATIVE_INFINITY} if no values were
279      * recorded
280      */
getMax()281     public final double getMax() {
282         return max;
283     }
284 
285     /**
286      * Returns the arithmetic mean of values recorded, or zero if no
287      * values have been recorded.
288      *
289      * <p> The computed average can vary numerically and have the
290      * special case behavior as computing the sum; see {@link #getSum}
291      * for details.
292      *
293      * @apiNote Values sorted by increasing absolute magnitude tend to yield
294      * more accurate results.
295      *
296      * @return the arithmetic mean of values, or zero if none
297      */
getAverage()298     public final double getAverage() {
299         return getCount() > 0 ? getSum() / getCount() : 0.0d;
300     }
301 
302     /**
303      * Returns a non-empty string representation of this object suitable for
304      * debugging. The exact presentation format is unspecified and may vary
305      * between implementations and versions.
306      */
307     @Override
toString()308     public String toString() {
309         return String.format(
310             "%s{count=%d, sum=%f, min=%f, average=%f, max=%f}",
311             this.getClass().getSimpleName(),
312             getCount(),
313             getSum(),
314             getMin(),
315             getAverage(),
316             getMax());
317     }
318 }
319