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 squares of the available values. Uses the following definition:
23   *
24   * <p>\[ \sum_{i=1}^n x_i^2 \]
25   *
26   * <p>where \( n \) is the number of samples.
27   *
28   * <ul>
29   *   <li>The result is zero if no values are observed.
30   * </ul>
31   *
32   * <p>The implementation uses an exact integer sum to compute the sum of squared values.
33   * The exact sum is returned using {@link #getAsBigInteger()}. Methods that return {@code int} or
34   * {@code long} primitives will raise an exception if the result overflows.
35   *
36   * <p>Note that the implementation does not use {@code BigInteger} arithmetic; for
37   * performance the sum is computed using primitives to create an unsigned 128-bit integer.
38   * Support is provided for at least 2<sup>63</sup> observations.
39   *
40   * <p>This class is designed to work with (though does not require)
41   * {@linkplain java.util.stream streams}.
42   *
43   * <p><strong>This implementation is not thread safe.</strong>
44   * If multiple threads access an instance of this class concurrently,
45   * and at least one of the threads invokes the {@link java.util.function.IntConsumer#accept(int) accept} or
46   * {@link StatisticAccumulator#combine(StatisticResult) combine} method, it must be synchronized externally.
47   *
48   * <p>However, it is safe to use {@link java.util.function.IntConsumer#accept(int) accept}
49   * and {@link StatisticAccumulator#combine(StatisticResult) combine}
50   * as {@code accumulator} and {@code combiner} functions of
51   * {@link java.util.stream.Collector Collector} on a parallel stream,
52   * because the parallel implementation of {@link java.util.stream.Stream#collect Stream.collect()}
53   * provides the necessary partitioning, isolation, and merging of results for
54   * safe and efficient parallel execution.
55   *
56   * @since 1.1
57   */
58  public final class IntSumOfSquares implements IntStatistic, StatisticAccumulator<IntSumOfSquares> {
59      /** Small array sample size.
60       * Used to avoid computing with UInt96 then converting to UInt128. */
61      private static final int SMALL_SAMPLE = 10;
62  
63      /** Sum of the squared values. */
64      private final UInt128 sumSq;
65  
66      /**
67       * Create an instance.
68       */
69      private IntSumOfSquares() {
70          this(UInt128.create());
71      }
72  
73      /**
74       * Create an instance.
75       *
76       * @param sumSq Sum of the squared values.
77       */
78      private IntSumOfSquares(UInt128 sumSq) {
79          this.sumSq = sumSq;
80      }
81  
82      /**
83       * Creates an instance.
84       *
85       * <p>The initial result is zero.
86       *
87       * @return {@code IntSumOfSquares} instance.
88       */
89      public static IntSumOfSquares create() {
90          return new IntSumOfSquares();
91      }
92  
93      /**
94       * Returns an instance populated using the input {@code values}.
95       *
96       * @param values Values.
97       * @return {@code IntSumOfSquares} instance.
98       */
99      public static IntSumOfSquares of(int... values) {
100         // Small arrays can be processed using the object
101         if (values.length < SMALL_SAMPLE) {
102             final IntSumOfSquares stat = new IntSumOfSquares();
103             for (final int x : values) {
104                 stat.accept(x);
105             }
106             return stat;
107         }
108 
109         // Arrays can be processed using specialised counts knowing the maximum limit
110         // for an array is 2^31 values.
111         final UInt96 ss = UInt96.create();
112         // Process pairs as we know two maximum value int^2 will not overflow
113         // an unsigned long.
114         final int end = values.length & ~0x1;
115         for (int i = 0; i < end; i += 2) {
116             final long x = values[i];
117             final long y = values[i + 1];
118             ss.addPositive(x * x + y * y);
119         }
120         if (end < values.length) {
121             final long x = values[end];
122             ss.addPositive(x * x);
123         }
124 
125         // Convert
126         return new IntSumOfSquares(UInt128.of(ss));
127     }
128 
129     /**
130      * Gets the sum of squares.
131      *
132      * <p>This is package private for use in {@link IntStatistics}.
133      *
134      * @return the sum of squares
135      */
136     UInt128 getSumOfSquares() {
137         return sumSq;
138     }
139 
140     /**
141      * Updates the state of the statistic to reflect the addition of {@code value}.
142      *
143      * @param value Value.
144      */
145     @Override
146     public void accept(int value) {
147         sumSq.addPositive((long) value * value);
148     }
149 
150     /**
151      * Gets the sum of squares of all input values.
152      *
153      * <p>When no values have been added, the result is zero.
154      *
155      * <p>Warning: This will raise an {@link ArithmeticException}
156      * if the result is not within the range {@code [0, 2^31)}.
157      *
158      * @return sum of all values.
159      * @throws ArithmeticException if the {@code result} overflows an {@code int}
160      * @see #getAsBigInteger()
161      */
162     @Override
163     public int getAsInt() {
164         return sumSq.toIntExact();
165     }
166 
167     /**
168      * Gets the sum of squares of all input values.
169      *
170      * <p>When no values have been added, the result is zero.
171      *
172      * <p>Warning: This will raise an {@link ArithmeticException}
173      * if the result is not within the range {@code [0, 2^63)}.
174      *
175      * @return sum of all values.
176      * @throws ArithmeticException if the {@code result} overflows a {@code long}
177      * @see #getAsBigInteger()
178      */
179     @Override
180     public long getAsLong() {
181         return sumSq.toLongExact();
182     }
183 
184     /**
185      * Gets the sum of squares of all input values.
186      *
187      * <p>When no values have been added, the result is zero.
188      *
189      * <p>Note that this conversion can lose information about the precision of the
190      * {@code BigInteger} value.
191      *
192      * @return sum of squares of all values.
193      * @see #getAsBigInteger()
194      */
195     @Override
196     public double getAsDouble() {
197         return sumSq.toDouble();
198     }
199 
200     /**
201      * Gets the sum of squares of all input values.
202      *
203      * <p>When no values have been added, the result is zero.
204      *
205      * @return sum of squares of all values.
206      */
207     @Override
208     public BigInteger getAsBigInteger() {
209         return sumSq.toBigInteger();
210     }
211 
212     @Override
213     public IntSumOfSquares combine(IntSumOfSquares other) {
214         sumSq.add(other.sumSq);
215         return this;
216     }
217 }