1 /*
2  * Copyright (c) 2013, 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.
8  *
9  * This code is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12  * version 2 for more details (a copy is included in the LICENSE file that
13  * accompanied this code).
14  *
15  * You should have received a copy of the GNU General Public License version
16  * 2 along with this work; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18  *
19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20  * or visit www.oracle.com if you need additional information or have any
21  * questions.
22  */
23 
24 package test.java.util.stream;
25 
26 import java.util.*;
27 import java.util.function.*;
28 import java.util.stream.*;
29 
30 import static java.lang.Double.*;
31 
32 /*
33  * @test
34  * @bug 8006572 8030212
35  * @summary Test for use of non-naive summation in stream-related sum and average operations.
36  */
37 public class TestDoubleSumAverage {
main(String... args)38     public static void main(String... args) {
39         int failures = 0;
40 
41         failures += testZeroAverageOfNonEmptyStream();
42         failures += testForCompenstation();
43         failures += testNonfiniteSum();
44 
45         if (failures > 0) {
46             throw new RuntimeException("Found " + failures + " numerical failure(s).");
47         }
48     }
49 
50     /**
51      * Test to verify that a non-empty stream with a zero average is non-empty.
52      */
testZeroAverageOfNonEmptyStream()53     private static int testZeroAverageOfNonEmptyStream() {
54         Supplier<DoubleStream> ds = () -> DoubleStream.iterate(0.0, e -> 0.0).limit(10);
55 
56         return  compareUlpDifference(0.0, ds.get().average().getAsDouble(), 0);
57     }
58 
59     /**
60      * Compute the sum and average of a sequence of double values in
61      * various ways and report an error if naive summation is used.
62      */
testForCompenstation()63     private static int testForCompenstation() {
64         int failures = 0;
65 
66         /*
67          * The exact sum of the test stream is 1 + 1e6*ulp(1.0) but a
68          * naive summation algorithm will return 1.0 since (1.0 +
69          * ulp(1.0)/2) will round to 1.0 again.
70          */
71         double base = 1.0;
72         double increment = Math.ulp(base)/2.0;
73         int count = 1_000_001;
74 
75         double expectedSum = base + (increment * (count - 1));
76         double expectedAvg = expectedSum / count;
77 
78         // Factory for double a stream of [base, increment, ..., increment] limited to a size of count
79         Supplier<DoubleStream> ds = () -> DoubleStream.iterate(base, e -> increment).limit(count);
80 
81         DoubleSummaryStatistics stats = ds.get().collect(DoubleSummaryStatistics::new,
82                                                          DoubleSummaryStatistics::accept,
83                                                          DoubleSummaryStatistics::combine);
84 
85         failures += compareUlpDifference(expectedSum, stats.getSum(), 3);
86         failures += compareUlpDifference(expectedAvg, stats.getAverage(), 3);
87 
88         failures += compareUlpDifference(expectedSum,
89                                          ds.get().sum(), 3);
90         failures += compareUlpDifference(expectedAvg,
91                                          ds.get().average().getAsDouble(), 3);
92 
93         failures += compareUlpDifference(expectedSum,
94                                          ds.get().boxed().collect(Collectors.summingDouble(d -> d)), 3);
95         failures += compareUlpDifference(expectedAvg,
96                                          ds.get().boxed().collect(Collectors.averagingDouble(d -> d)),3);
97         return failures;
98     }
99 
testNonfiniteSum()100     private static int testNonfiniteSum() {
101         int failures = 0;
102 
103         Map<Supplier<DoubleStream>, Double> testCases = new LinkedHashMap<>();
104         testCases.put(() -> DoubleStream.of(MAX_VALUE, MAX_VALUE),   POSITIVE_INFINITY);
105         testCases.put(() -> DoubleStream.of(-MAX_VALUE, -MAX_VALUE), NEGATIVE_INFINITY);
106 
107         testCases.put(() -> DoubleStream.of(1.0d, POSITIVE_INFINITY, 1.0d), POSITIVE_INFINITY);
108         testCases.put(() -> DoubleStream.of(POSITIVE_INFINITY),             POSITIVE_INFINITY);
109         testCases.put(() -> DoubleStream.of(POSITIVE_INFINITY, POSITIVE_INFINITY), POSITIVE_INFINITY);
110         testCases.put(() -> DoubleStream.of(POSITIVE_INFINITY, POSITIVE_INFINITY, 0.0), POSITIVE_INFINITY);
111 
112         testCases.put(() -> DoubleStream.of(1.0d, NEGATIVE_INFINITY, 1.0d), NEGATIVE_INFINITY);
113         testCases.put(() -> DoubleStream.of(NEGATIVE_INFINITY),             NEGATIVE_INFINITY);
114         testCases.put(() -> DoubleStream.of(NEGATIVE_INFINITY, NEGATIVE_INFINITY), NEGATIVE_INFINITY);
115         testCases.put(() -> DoubleStream.of(NEGATIVE_INFINITY, NEGATIVE_INFINITY, 0.0), NEGATIVE_INFINITY);
116 
117         testCases.put(() -> DoubleStream.of(1.0d, NaN, 1.0d),               NaN);
118         testCases.put(() -> DoubleStream.of(NaN),                           NaN);
119         testCases.put(() -> DoubleStream.of(1.0d, NEGATIVE_INFINITY, POSITIVE_INFINITY, 1.0d), NaN);
120         testCases.put(() -> DoubleStream.of(1.0d, POSITIVE_INFINITY, NEGATIVE_INFINITY, 1.0d), NaN);
121         testCases.put(() -> DoubleStream.of(POSITIVE_INFINITY, NaN), NaN);
122         testCases.put(() -> DoubleStream.of(NEGATIVE_INFINITY, NaN), NaN);
123         testCases.put(() -> DoubleStream.of(NaN, POSITIVE_INFINITY), NaN);
124         testCases.put(() -> DoubleStream.of(NaN, NEGATIVE_INFINITY), NaN);
125 
126         for(Map.Entry<Supplier<DoubleStream>, Double> testCase : testCases.entrySet()) {
127             Supplier<DoubleStream> ds = testCase.getKey();
128             double expected = testCase.getValue();
129 
130             DoubleSummaryStatistics stats = ds.get().collect(DoubleSummaryStatistics::new,
131                                                              DoubleSummaryStatistics::accept,
132                                                              DoubleSummaryStatistics::combine);
133 
134             failures += compareUlpDifference(expected, stats.getSum(), 0);
135             failures += compareUlpDifference(expected, stats.getAverage(), 0);
136 
137             failures += compareUlpDifference(expected, ds.get().sum(), 0);
138             failures += compareUlpDifference(expected, ds.get().average().getAsDouble(), 0);
139 
140             failures += compareUlpDifference(expected, ds.get().boxed().collect(Collectors.summingDouble(d -> d)), 0);
141             failures += compareUlpDifference(expected, ds.get().boxed().collect(Collectors.averagingDouble(d -> d)), 0);
142         }
143 
144         return failures;
145     }
146 
147     /**
148      * Compute the ulp difference of two double values and compare against an error threshold.
149      */
compareUlpDifference(double expected, double computed, double threshold)150     private static int compareUlpDifference(double expected, double computed, double threshold) {
151         if (!Double.isFinite(expected)) {
152             // Handle NaN and infinity cases
153             if (Double.compare(expected, computed) == 0)
154                 return 0;
155             else {
156                 System.err.printf("Unexpected sum, %g rather than %g.%n",
157                                   computed, expected);
158                 return 1;
159             }
160         }
161 
162         double ulpDifference = Math.abs(expected - computed) / Math.ulp(expected);
163 
164         if (ulpDifference > threshold) {
165             System.err.printf("Numerical summation error too large, %g ulps rather than %g.%n",
166                               ulpDifference, threshold);
167             return 1;
168         } else
169             return 0;
170     }
171 }
172