View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.statistics.descriptive;
18  
19  import java.math.BigInteger;
20  
21  /**
22   * Returns the sum of the available values.
23   *
24   * <ul>
25   *   <li>The result is zero if no values are added.
26   * </ul>
27   *
28   * <p>This class uses an exact integer sum. The exact sum is
29   * returned using {@link #getAsBigInteger()}. Methods that return {@code int} or
30   * {@code long} primitives will raise an exception if the result overflows.
31   * The {@code long} value is safe up to the maximum array length for any input
32   * {@code int[]} data. The {@code long} value can overflow when instances are combined.
33   *
34   * <p>Note that the implementation does not use {@code BigInteger} arithmetic; for
35   * performance the sum is computed using primitives to create a signed 128-bit integer.
36   * Support is provided for at least 2<sup>63</sup> observations.
37   *
38   * <p>This class is designed to work with (though does not require)
39   * {@linkplain java.util.stream streams}.
40   *
41   * <p><strong>This implementation is not thread safe.</strong>
42   * If multiple threads access an instance of this class concurrently,
43   * and at least one of the threads invokes the {@link java.util.function.IntConsumer#accept(int) accept} or
44   * {@link StatisticAccumulator#combine(StatisticResult) combine} method, it must be synchronized externally.
45   *
46   * <p>However, it is safe to use {@link java.util.function.IntConsumer#accept(int) accept}
47   * and {@link StatisticAccumulator#combine(StatisticResult) combine}
48   * as {@code accumulator} and {@code combiner} functions of
49   * {@link java.util.stream.Collector Collector} on a parallel stream,
50   * because the parallel implementation of {@link java.util.stream.Stream#collect Stream.collect()}
51   * provides the necessary partitioning, isolation, and merging of results for
52   * safe and efficient parallel execution.
53   *
54   * @since 1.1
55   */
56  public final class IntSum implements IntStatistic, StatisticAccumulator<IntSum> {
57      /** Sum of the values. */
58      private final Int128 sum;
59  
60      /**
61       * Create an instance.
62       */
63      private IntSum() {
64          this(Int128.create());
65      }
66  
67      /**
68       * Create an instance.
69       *
70       * @param sum Sum of the values.
71       */
72      private IntSum(Int128 sum) {
73          this.sum = sum;
74      }
75  
76      /**
77       * Creates an instance.
78       *
79       * <p>The initial result is zero.
80       *
81       * @return {@code IntSum} instance.
82       */
83      public static IntSum create() {
84          return new IntSum();
85      }
86  
87      /**
88       * Returns an instance populated using the input {@code values}.
89       *
90       * <p>When the input is an empty array, the result is zero.
91       *
92       * <p>The {@link #getAsLong()} result is valid for any input {@code int[]} length;
93       * the {@link #getAsInt()} result may overflow.
94       *
95       * @param values Values.
96       * @return {@code IntSum} instance.
97       */
98      public static IntSum of(int... values) {
99          // Sum of an array cannot exceed a 64-bit long
100         long s = 0;
101         for (final int x : values) {
102             s += x;
103         }
104         // Convert
105         return new IntSum(Int128.of(s));
106     }
107 
108     /**
109      * Returns an instance populated using the specified range of {@code values}.
110      *
111      * <p>When the range is empty, the result is zero.
112      *
113      * <p>The {@link #getAsLong()} result is valid for any range length;
114      * the {@link #getAsInt()} result may overflow.
115      *
116      * @param values Values.
117      * @param from Inclusive start of the range.
118      * @param to Exclusive end of the range.
119      * @return {@code IntSum} instance.
120      * @throws IndexOutOfBoundsException if the sub-range is out of bounds
121      * @since 1.2
122      */
123     public static IntSum ofRange(int[] values, int from, int to) {
124         Statistics.checkFromToIndex(from, to, values.length);
125         return createFromRange(values, from, to);
126     }
127 
128     /**
129      * Create an instance using the specified range of {@code values}.
130      *
131      * <p>Warning: No range checks are performed.
132      *
133      * @param values Values.
134      * @param from Inclusive start of the range.
135      * @param to Exclusive end of the range.
136      * @return {@code IntSum} instance.
137      */
138     static IntSum createFromRange(int[] values, int from, int to) {
139         // Sum of an array cannot exceed a 64-bit long
140         long s = 0;
141         for (int i = from; i < to; i++) {
142             s += values[i];
143         }
144         // Convert
145         return new IntSum(Int128.of(s));
146     }
147 
148     /**
149      * Gets the sum.
150      *
151      * <p>This is package private for use in {@link IntStatistics}.
152      *
153      * @return the sum
154      */
155     Int128 getSum() {
156         return sum;
157     }
158 
159     /**
160      * Updates the state of the statistic to reflect the addition of {@code value}.
161      *
162      * @param value Value.
163      */
164     @Override
165     public void accept(int value) {
166         sum.add(value);
167     }
168 
169     /**
170      * Gets the sum of all input values.
171      *
172      * <p>When no values have been added, the result is zero.
173      *
174      * <p>Warning: This will raise an {@link ArithmeticException}
175      * if the result is not within the range {@code [-2^31, 2^31)}.
176      *
177      * @return sum of all values.
178      * @throws ArithmeticException if the {@code result} overflows an {@code int}
179      * @see #getAsBigInteger()
180      */
181     @Override
182     public int getAsInt() {
183         return sum.toIntExact();
184     }
185 
186     /**
187      * Gets the sum of all input values.
188      *
189      * <p>When no values have been added, the result is zero.
190      *
191      * <p>Warning: This will raise an {@link ArithmeticException}
192      * if the result is not within the range {@code [-2^63, 2^63)}.
193      *
194      * @return sum of all values.
195      * @throws ArithmeticException if the {@code result} overflows a {@code long}
196      * @see #getAsBigInteger()
197      */
198     @Override
199     public long getAsLong() {
200         return sum.toLongExact();
201     }
202 
203     /**
204      * Gets the sum of all input values.
205      *
206      * <p>When no values have been added, the result is zero.
207      *
208      * <p>Note that this conversion can lose information about the precision of the
209      * {@code BigInteger} value.
210      *
211      * @return sum of all values.
212      * @see #getAsBigInteger()
213      */
214     @Override
215     public double getAsDouble() {
216         return sum.toDouble();
217     }
218 
219     /**
220      * Gets the sum of all input values.
221      *
222      * <p>When no values have been added, the result is zero.
223      *
224      * @return sum of all values.
225      */
226     @Override
227     public BigInteger getAsBigInteger() {
228         return sum.toBigInteger();
229     }
230 
231     @Override
232     public IntSum combine(IntSum other) {
233         sum.add(other.sum);
234         return this;
235     }
236 }