Path: blob/master/src/java.base/share/classes/java/util/DoubleSummaryStatistics.java
41152 views
/*1* Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/24package java.util;2526import java.util.function.DoubleConsumer;27import java.util.stream.Collector;28import java.util.stream.DoubleStream;2930/**31* A state object for collecting statistics such as count, min, max, sum, and32* average.33*34* <p>This class is designed to work with (though does not require)35* {@linkplain java.util.stream streams}. For example, you can compute36* summary statistics on a stream of doubles with:37* <pre> {@code38* DoubleSummaryStatistics stats = doubleStream.collect(DoubleSummaryStatistics::new,39* DoubleSummaryStatistics::accept,40* DoubleSummaryStatistics::combine);41* }</pre>42*43* <p>{@code DoubleSummaryStatistics} can be used as a44* {@linkplain java.util.stream.Stream#collect(Collector) reduction}45* target for a {@linkplain java.util.stream.Stream stream}. For example:46*47* <pre> {@code48* DoubleSummaryStatistics stats = people.stream()49* .collect(Collectors.summarizingDouble(Person::getWeight));50*}</pre>51*52* This computes, in a single pass, the count of people, as well as the minimum,53* maximum, sum, and average of their weights.54*55* @implNote This implementation is not thread safe. However, it is safe to use56* {@link java.util.stream.Collectors#summarizingDouble(java.util.function.ToDoubleFunction)57* Collectors.summarizingDouble()} on a parallel stream, because the parallel58* implementation of {@link java.util.stream.Stream#collect Stream.collect()}59* provides the necessary partitioning, isolation, and merging of results for60* safe and efficient parallel execution.61*62* <p>This implementation does not check for overflow of the count.63* @since 1.864*/65public class DoubleSummaryStatistics implements DoubleConsumer {66private long count;67private double sum;68private double sumCompensation; // Low order bits of sum69private double simpleSum; // Used to compute right sum for non-finite inputs70private double min = Double.POSITIVE_INFINITY;71private double max = Double.NEGATIVE_INFINITY;7273/**74* Constructs an empty instance with zero count, zero sum,75* {@code Double.POSITIVE_INFINITY} min, {@code Double.NEGATIVE_INFINITY}76* max and zero average.77*/78public DoubleSummaryStatistics() { }7980/**81* Constructs a non-empty instance with the specified {@code count},82* {@code min}, {@code max}, and {@code sum}.83*84* <p>If {@code count} is zero then the remaining arguments are ignored and85* an empty instance is constructed.86*87* <p>If the arguments are inconsistent then an {@code IllegalArgumentException}88* is thrown. The necessary consistent argument conditions are:89* <ul>90* <li>{@code count >= 0}</li>91* <li>{@code (min <= max && !isNaN(sum)) || (isNaN(min) && isNaN(max) && isNaN(sum))}</li>92* </ul>93* @apiNote94* The enforcement of argument correctness means that the retrieved set of95* recorded values obtained from a {@code DoubleSummaryStatistics} source96* instance may not be a legal set of arguments for this constructor due to97* arithmetic overflow of the source's recorded count of values.98* The consistent argument conditions are not sufficient to prevent the99* creation of an internally inconsistent instance. An example of such a100* state would be an instance with: {@code count} = 2, {@code min} = 1,101* {@code max} = 2, and {@code sum} = 0.102*103* @param count the count of values104* @param min the minimum value105* @param max the maximum value106* @param sum the sum of all values107* @throws IllegalArgumentException if the arguments are inconsistent108* @since 10109*/110public DoubleSummaryStatistics(long count, double min, double max, double sum)111throws IllegalArgumentException {112if (count < 0L) {113throw new IllegalArgumentException("Negative count value");114} else if (count > 0L) {115if (min > max)116throw new IllegalArgumentException("Minimum greater than maximum");117118// All NaN or non NaN119var ncount = DoubleStream.of(min, max, sum).filter(Double::isNaN).count();120if (ncount > 0 && ncount < 3)121throw new IllegalArgumentException("Some, not all, of the minimum, maximum, or sum is NaN");122123this.count = count;124this.sum = sum;125this.simpleSum = sum;126this.sumCompensation = 0.0d;127this.min = min;128this.max = max;129}130// Use default field values if count == 0131}132133/**134* Records another value into the summary information.135*136* @param value the input value137*/138@Override139public void accept(double value) {140++count;141simpleSum += value;142sumWithCompensation(value);143min = Math.min(min, value);144max = Math.max(max, value);145}146147/**148* Combines the state of another {@code DoubleSummaryStatistics} into this149* one.150*151* @param other another {@code DoubleSummaryStatistics}152* @throws NullPointerException if {@code other} is null153*/154public void combine(DoubleSummaryStatistics other) {155count += other.count;156simpleSum += other.simpleSum;157sumWithCompensation(other.sum);158sumWithCompensation(other.sumCompensation);159min = Math.min(min, other.min);160max = Math.max(max, other.max);161}162163/**164* Incorporate a new double value using Kahan summation /165* compensated summation.166*/167private void sumWithCompensation(double value) {168double tmp = value - sumCompensation;169double velvel = sum + tmp; // Little wolf of rounding error170sumCompensation = (velvel - sum) - tmp;171sum = velvel;172}173174/**175* Return the count of values recorded.176*177* @return the count of values178*/179public final long getCount() {180return count;181}182183/**184* Returns the sum of values recorded, or zero if no values have been185* recorded.186*187* <p> The value of a floating-point sum is a function both of the188* input values as well as the order of addition operations. The189* order of addition operations of this method is intentionally190* not defined to allow for implementation flexibility to improve191* the speed and accuracy of the computed result.192*193* In particular, this method may be implemented using compensated194* summation or other technique to reduce the error bound in the195* numerical sum compared to a simple summation of {@code double}196* values.197*198* Because of the unspecified order of operations and the199* possibility of using differing summation schemes, the output of200* this method may vary on the same input values.201*202* <p>Various conditions can result in a non-finite sum being203* computed. This can occur even if the all the recorded values204* being summed are finite. If any recorded value is non-finite,205* the sum will be non-finite:206*207* <ul>208*209* <li>If any recorded value is a NaN, then the final sum will be210* NaN.211*212* <li>If the recorded values contain one or more infinities, the213* sum will be infinite or NaN.214*215* <ul>216*217* <li>If the recorded values contain infinities of opposite sign,218* the sum will be NaN.219*220* <li>If the recorded values contain infinities of one sign and221* an intermediate sum overflows to an infinity of the opposite222* sign, the sum may be NaN.223*224* </ul>225*226* </ul>227*228* It is possible for intermediate sums of finite values to229* overflow into opposite-signed infinities; if that occurs, the230* final sum will be NaN even if the recorded values are all231* finite.232*233* If all the recorded values are zero, the sign of zero is234* <em>not</em> guaranteed to be preserved in the final sum.235*236* @apiNote Values sorted by increasing absolute magnitude tend to yield237* more accurate results.238*239* @return the sum of values, or zero if none240*/241public final double getSum() {242// Better error bounds to add both terms as the final sum243double tmp = sum + sumCompensation;244if (Double.isNaN(tmp) && Double.isInfinite(simpleSum))245// If the compensated sum is spuriously NaN from246// accumulating one or more same-signed infinite values,247// return the correctly-signed infinity stored in248// simpleSum.249return simpleSum;250else251return tmp;252}253254/**255* Returns the minimum recorded value, {@code Double.NaN} if any recorded256* value was NaN or {@code Double.POSITIVE_INFINITY} if no values were257* recorded. Unlike the numerical comparison operators, this method258* considers negative zero to be strictly smaller than positive zero.259*260* @return the minimum recorded value, {@code Double.NaN} if any recorded261* value was NaN or {@code Double.POSITIVE_INFINITY} if no values were262* recorded263*/264public final double getMin() {265return min;266}267268/**269* Returns the maximum recorded value, {@code Double.NaN} if any recorded270* value was NaN or {@code Double.NEGATIVE_INFINITY} if no values were271* recorded. Unlike the numerical comparison operators, this method272* considers negative zero to be strictly smaller than positive zero.273*274* @return the maximum recorded value, {@code Double.NaN} if any recorded275* value was NaN or {@code Double.NEGATIVE_INFINITY} if no values were276* recorded277*/278public final double getMax() {279return max;280}281282/**283* Returns the arithmetic mean of values recorded, or zero if no284* values have been recorded.285*286* <p> The computed average can vary numerically and have the287* special case behavior as computing the sum; see {@link #getSum}288* for details.289*290* @apiNote Values sorted by increasing absolute magnitude tend to yield291* more accurate results.292*293* @return the arithmetic mean of values, or zero if none294*/295public final double getAverage() {296return getCount() > 0 ? getSum() / getCount() : 0.0d;297}298299/**300* Returns a non-empty string representation of this object suitable for301* debugging. The exact presentation format is unspecified and may vary302* between implementations and versions.303*/304@Override305public String toString() {306return String.format(307"%s{count=%d, sum=%f, min=%f, average=%f, max=%f}",308this.getClass().getSimpleName(),309getCount(),310getSum(),311getMin(),312getAverage(),313getMax());314}315}316317318