Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/util/DoubleSummaryStatistics.java
38829 views
/*1* Copyright (c) 2012, 2013, 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;2829/**30* A state object for collecting statistics such as count, min, max, sum, and31* average.32*33* <p>This class is designed to work with (though does not require)34* {@linkplain java.util.stream streams}. For example, you can compute35* summary statistics on a stream of doubles with:36* <pre> {@code37* DoubleSummaryStatistics stats = doubleStream.collect(DoubleSummaryStatistics::new,38* DoubleSummaryStatistics::accept,39* DoubleSummaryStatistics::combine);40* }</pre>41*42* <p>{@code DoubleSummaryStatistics} can be used as a43* {@linkplain java.util.stream.Stream#collect(Collector) reduction}44* target for a {@linkplain java.util.stream.Stream stream}. For example:45*46* <pre> {@code47* DoubleSummaryStatistics stats = people.stream()48* .collect(Collectors.summarizingDouble(Person::getWeight));49*}</pre>50*51* This computes, in a single pass, the count of people, as well as the minimum,52* maximum, sum, and average of their weights.53*54* @implNote This implementation is not thread safe. However, it is safe to use55* {@link java.util.stream.Collectors#summarizingDouble(java.util.function.ToDoubleFunction)56* Collectors.toDoubleStatistics()} on a parallel stream, because the parallel57* implementation of {@link java.util.stream.Stream#collect Stream.collect()}58* provides the necessary partitioning, isolation, and merging of results for59* safe and efficient parallel execution.60* @since 1.861*/62public class DoubleSummaryStatistics implements DoubleConsumer {63private long count;64private double sum;65private double sumCompensation; // Low order bits of sum66private double simpleSum; // Used to compute right sum for non-finite inputs67private double min = Double.POSITIVE_INFINITY;68private double max = Double.NEGATIVE_INFINITY;6970/**71* Construct an empty instance with zero count, zero sum,72* {@code Double.POSITIVE_INFINITY} min, {@code Double.NEGATIVE_INFINITY}73* max and zero average.74*/75public DoubleSummaryStatistics() { }7677/**78* Records another value into the summary information.79*80* @param value the input value81*/82@Override83public void accept(double value) {84++count;85simpleSum += value;86sumWithCompensation(value);87min = Math.min(min, value);88max = Math.max(max, value);89}9091/**92* Combines the state of another {@code DoubleSummaryStatistics} into this93* one.94*95* @param other another {@code DoubleSummaryStatistics}96* @throws NullPointerException if {@code other} is null97*/98public void combine(DoubleSummaryStatistics other) {99count += other.count;100simpleSum += other.simpleSum;101sumWithCompensation(other.sum);102sumWithCompensation(other.sumCompensation);103min = Math.min(min, other.min);104max = Math.max(max, other.max);105}106107/**108* Incorporate a new double value using Kahan summation /109* compensated summation.110*/111private void sumWithCompensation(double value) {112double tmp = value - sumCompensation;113double velvel = sum + tmp; // Little wolf of rounding error114sumCompensation = (velvel - sum) - tmp;115sum = velvel;116}117118/**119* Return the count of values recorded.120*121* @return the count of values122*/123public final long getCount() {124return count;125}126127/**128* Returns the sum of values recorded, or zero if no values have been129* recorded.130*131* If any recorded value is a NaN or the sum is at any point a NaN132* then the sum will be NaN.133*134* <p> The value of a floating-point sum is a function both of the135* input values as well as the order of addition operations. The136* order of addition operations of this method is intentionally137* not defined to allow for implementation flexibility to improve138* the speed and accuracy of the computed result.139*140* In particular, this method may be implemented using compensated141* summation or other technique to reduce the error bound in the142* numerical sum compared to a simple summation of {@code double}143* values.144*145* @apiNote Values sorted by increasing absolute magnitude tend to yield146* more accurate results.147*148* @return the sum of values, or zero if none149*/150public final double getSum() {151// Better error bounds to add both terms as the final sum152double tmp = sum + sumCompensation;153if (Double.isNaN(tmp) && Double.isInfinite(simpleSum))154// If the compensated sum is spuriously NaN from155// accumulating one or more same-signed infinite values,156// return the correctly-signed infinity stored in157// simpleSum.158return simpleSum;159else160return tmp;161}162163/**164* Returns the minimum recorded value, {@code Double.NaN} if any recorded165* value was NaN or {@code Double.POSITIVE_INFINITY} if no values were166* recorded. Unlike the numerical comparison operators, this method167* considers negative zero to be strictly smaller than positive zero.168*169* @return the minimum recorded value, {@code Double.NaN} if any recorded170* value was NaN or {@code Double.POSITIVE_INFINITY} if no values were171* recorded172*/173public final double getMin() {174return min;175}176177/**178* Returns the maximum recorded value, {@code Double.NaN} if any recorded179* value was NaN or {@code Double.NEGATIVE_INFINITY} if no values were180* recorded. Unlike the numerical comparison operators, this method181* considers negative zero to be strictly smaller than positive zero.182*183* @return the maximum recorded value, {@code Double.NaN} if any recorded184* value was NaN or {@code Double.NEGATIVE_INFINITY} if no values were185* recorded186*/187public final double getMax() {188return max;189}190191/**192* Returns the arithmetic mean of values recorded, or zero if no193* values have been recorded.194*195* If any recorded value is a NaN or the sum is at any point a NaN196* then the average will be code NaN.197*198* <p>The average returned can vary depending upon the order in199* which values are recorded.200*201* This method may be implemented using compensated summation or202* other technique to reduce the error bound in the {@link #getSum203* numerical sum} used to compute the average.204*205* @apiNote Values sorted by increasing absolute magnitude tend to yield206* more accurate results.207*208* @return the arithmetic mean of values, or zero if none209*/210public final double getAverage() {211return getCount() > 0 ? getSum() / getCount() : 0.0d;212}213214/**215* {@inheritDoc}216*217* Returns a non-empty string representation of this object suitable for218* debugging. The exact presentation format is unspecified and may vary219* between implementations and versions.220*/221@Override222public String toString() {223return String.format(224"%s{count=%d, sum=%f, min=%f, average=%f, max=%f}",225this.getClass().getSimpleName(),226getCount(),227getSum(),228getMin(),229getAverage(),230getMax());231}232}233234235