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