Path: blob/master/src/java.base/share/classes/java/util/DoubleSummaryStatistics.java
67862 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);158159// Subtract compensation bits160sumWithCompensation(-other.sumCompensation);161min = Math.min(min, other.min);162max = Math.max(max, other.max);163}164165/**166* Incorporate a new double value using Kahan summation /167* compensated summation.168*/169private void sumWithCompensation(double value) {170double tmp = value - sumCompensation;171double velvel = sum + tmp; // Little wolf of rounding error172sumCompensation = (velvel - sum) - tmp;173sum = velvel;174}175176/**177* Return the count of values recorded.178*179* @return the count of values180*/181public final long getCount() {182return count;183}184185/**186* Returns the sum of values recorded, or zero if no values have been187* recorded.188*189* <p> The value of a floating-point sum is a function both of the190* input values as well as the order of addition operations. The191* order of addition operations of this method is intentionally192* not defined to allow for implementation flexibility to improve193* the speed and accuracy of the computed result.194*195* In particular, this method may be implemented using compensated196* summation or other technique to reduce the error bound in the197* numerical sum compared to a simple summation of {@code double}198* values.199*200* Because of the unspecified order of operations and the201* possibility of using differing summation schemes, the output of202* this method may vary on the same input values.203*204* <p>Various conditions can result in a non-finite sum being205* computed. This can occur even if the all the recorded values206* being summed are finite. If any recorded value is non-finite,207* the sum will be non-finite:208*209* <ul>210*211* <li>If any recorded value is a NaN, then the final sum will be212* NaN.213*214* <li>If the recorded values contain one or more infinities, the215* sum will be infinite or NaN.216*217* <ul>218*219* <li>If the recorded values contain infinities of opposite sign,220* the sum will be NaN.221*222* <li>If the recorded values contain infinities of one sign and223* an intermediate sum overflows to an infinity of the opposite224* sign, the sum may be NaN.225*226* </ul>227*228* </ul>229*230* It is possible for intermediate sums of finite values to231* overflow into opposite-signed infinities; if that occurs, the232* final sum will be NaN even if the recorded values are all233* finite.234*235* If all the recorded values are zero, the sign of zero is236* <em>not</em> guaranteed to be preserved in the final sum.237*238* @apiNote Values sorted by increasing absolute magnitude tend to yield239* more accurate results.240*241* @return the sum of values, or zero if none242*/243public final double getSum() {244// Better error bounds to add both terms as the final sum245double tmp = sum - sumCompensation;246if (Double.isNaN(tmp) && Double.isInfinite(simpleSum))247// If the compensated sum is spuriously NaN from248// accumulating one or more same-signed infinite values,249// return the correctly-signed infinity stored in250// simpleSum.251return simpleSum;252else253return tmp;254}255256/**257* Returns the minimum recorded value, {@code Double.NaN} if any recorded258* value was NaN or {@code Double.POSITIVE_INFINITY} if no values were259* recorded. Unlike the numerical comparison operators, this method260* considers negative zero to be strictly smaller than positive zero.261*262* @return the minimum recorded value, {@code Double.NaN} if any recorded263* value was NaN or {@code Double.POSITIVE_INFINITY} if no values were264* recorded265*/266public final double getMin() {267return min;268}269270/**271* Returns the maximum recorded value, {@code Double.NaN} if any recorded272* value was NaN or {@code Double.NEGATIVE_INFINITY} if no values were273* recorded. Unlike the numerical comparison operators, this method274* considers negative zero to be strictly smaller than positive zero.275*276* @return the maximum recorded value, {@code Double.NaN} if any recorded277* value was NaN or {@code Double.NEGATIVE_INFINITY} if no values were278* recorded279*/280public final double getMax() {281return max;282}283284/**285* Returns the arithmetic mean of values recorded, or zero if no286* values have been recorded.287*288* <p> The computed average can vary numerically and have the289* special case behavior as computing the sum; see {@link #getSum}290* for details.291*292* @apiNote Values sorted by increasing absolute magnitude tend to yield293* more accurate results.294*295* @return the arithmetic mean of values, or zero if none296*/297public final double getAverage() {298return getCount() > 0 ? getSum() / getCount() : 0.0d;299}300301/**302* Returns a non-empty string representation of this object suitable for303* debugging. The exact presentation format is unspecified and may vary304* between implementations and versions.305*/306@Override307public String toString() {308return String.format(309"%s{count=%d, sum=%f, min=%f, average=%f, max=%f}",310this.getClass().getSimpleName(),311getCount(),312getSum(),313getMin(),314getAverage(),315getMax());316}317}318319320