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      * Gets the sum.
110      *
111      * <p>This is package private for use in {@link IntStatistics}.
112      *
113      * @return the sum
114      */
115     Int128 getSum() {
116         return sum;
117     }
118 
119     /**
120      * Updates the state of the statistic to reflect the addition of {@code value}.
121      *
122      * @param value Value.
123      */
124     @Override
125     public void accept(int value) {
126         sum.add(value);
127     }
128 
129     /**
130      * Gets the sum of all input values.
131      *
132      * <p>When no values have been added, the result is zero.
133      *
134      * <p>Warning: This will raise an {@link ArithmeticException}
135      * if the result is not within the range {@code [-2^31, 2^31)}.
136      *
137      * @return sum of all values.
138      * @throws ArithmeticException if the {@code result} overflows an {@code int}
139      * @see #getAsBigInteger()
140      */
141     @Override
142     public int getAsInt() {
143         return sum.toIntExact();
144     }
145 
146     /**
147      * Gets the sum of all input values.
148      *
149      * <p>When no values have been added, the result is zero.
150      *
151      * <p>Warning: This will raise an {@link ArithmeticException}
152      * if the result is not within the range {@code [-2^63, 2^63)}.
153      *
154      * @return sum of all values.
155      * @throws ArithmeticException if the {@code result} overflows a {@code long}
156      * @see #getAsBigInteger()
157      */
158     @Override
159     public long getAsLong() {
160         return sum.toLongExact();
161     }
162 
163     /**
164      * Gets the sum of all input values.
165      *
166      * <p>When no values have been added, the result is zero.
167      *
168      * <p>Note that this conversion can lose information about the precision of the
169      * {@code BigInteger} value.
170      *
171      * @return sum of all values.
172      * @see #getAsBigInteger()
173      */
174     @Override
175     public double getAsDouble() {
176         return sum.toDouble();
177     }
178 
179     /**
180      * Gets the sum of all input values.
181      *
182      * <p>When no values have been added, the result is zero.
183      *
184      * @return sum of all values.
185      */
186     @Override
187     public BigInteger getAsBigInteger() {
188         return sum.toBigInteger();
189     }
190 
191     @Override
192     public IntSum combine(IntSum other) {
193         sum.add(other.sum);
194         return this;
195     }
196 }