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 192-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 LongSumOfSquares implements LongStatistic, StatisticAccumulator<LongSumOfSquares> {
59  
60      /** Sum of the squared values. */
61      private final UInt192 sumSq;
62  
63      /**
64       * Create an instance.
65       */
66      private LongSumOfSquares() {
67          this(UInt192.create());
68      }
69  
70      /**
71       * Create an instance.
72       *
73       * @param sumSq Sum of the squared values.
74       */
75      private LongSumOfSquares(UInt192 sumSq) {
76          this.sumSq = sumSq;
77      }
78  
79      /**
80       * Creates an instance.
81       *
82       * <p>The initial result is zero.
83       *
84       * @return {@code LongSumOfSquares} instance.
85       */
86      public static LongSumOfSquares create() {
87          return new LongSumOfSquares();
88      }
89  
90      /**
91       * Returns an instance populated using the input {@code values}.
92       *
93       * <p>When the input is an empty array, the result is zero.
94       *
95       * @param values Values.
96       * @return {@code LongSumOfSquares} instance.
97       */
98      public static LongSumOfSquares of(long... values) {
99          final UInt192 ss = UInt192.create();
100         for (final long x : values) {
101             ss.addSquare(x);
102         }
103         return new LongSumOfSquares(ss);
104     }
105 
106     /**
107      * Returns an instance populated using the specified range of {@code values}.
108      *
109      * <p>When the range is empty, the result is zero.
110      *
111      * @param values Values.
112      * @param from Inclusive start of the range.
113      * @param to Exclusive end of the range.
114      * @return {@code LongSumOfSquares} instance.
115      * @throws IndexOutOfBoundsException if the sub-range is out of bounds
116      * @since 1.2
117      */
118     public static LongSumOfSquares ofRange(long[] values, int from, int to) {
119         Statistics.checkFromToIndex(from, to, values.length);
120         return createFromRange(values, from, to);
121     }
122 
123     /**
124      * Create an instance using the specified range of {@code values}.
125      *
126      * <p>Warning: No range checks are performed.
127      *
128      * @param values Values.
129      * @param from Inclusive start of the range.
130      * @param to Exclusive end of the range.
131      * @return {@code LongSumOfSquares} instance.
132      */
133     static LongSumOfSquares createFromRange(long[] values, int from, int to) {
134         final UInt192 ss = UInt192.create();
135         for (int i = from; i < to; i++) {
136             ss.addSquare(values[i]);
137         }
138         return new LongSumOfSquares(ss);
139     }
140 
141     /**
142      * Gets the sum of squares.
143      *
144      * <p>This is package private for use in {@link IntStatistics}.
145      *
146      * @return the sum of squares
147      */
148     UInt192 getSumOfSquares() {
149         return sumSq;
150     }
151 
152     /**
153      * Updates the state of the statistic to reflect the addition of {@code value}.
154      *
155      * @param value Value.
156      */
157     @Override
158     public void accept(long value) {
159         sumSq.addSquare(value);
160     }
161 
162     /**
163      * Gets the sum of squares of all input values.
164      *
165      * <p>When no values have been added, the result is zero.
166      *
167      * <p>Warning: This will raise an {@link ArithmeticException}
168      * if the result is not within the range {@code [0, 2^31)}.
169      *
170      * @return sum of all values.
171      * @throws ArithmeticException if the {@code result} overflows an {@code int}
172      * @see #getAsBigInteger()
173      */
174     @Override
175     public int getAsInt() {
176         return sumSq.toIntExact();
177     }
178 
179     /**
180      * Gets the sum of squares of all input values.
181      *
182      * <p>When no values have been added, the result is zero.
183      *
184      * <p>Warning: This will raise an {@link ArithmeticException}
185      * if the result is not within the range {@code [0, 2^63)}.
186      *
187      * @return sum of all values.
188      * @throws ArithmeticException if the {@code result} overflows a {@code long}
189      * @see #getAsBigInteger()
190      */
191     @Override
192     public long getAsLong() {
193         return sumSq.toLongExact();
194     }
195 
196     /**
197      * Gets the sum of squares of all input values.
198      *
199      * <p>When no values have been added, the result is zero.
200      *
201      * <p>Note that this conversion can lose information about the precision of the
202      * {@code BigInteger} value.
203      *
204      * @return sum of squares of all values.
205      * @see #getAsBigInteger()
206      */
207     @Override
208     public double getAsDouble() {
209         return sumSq.toDouble();
210     }
211 
212     /**
213      * Gets the sum of squares of all input values.
214      *
215      * <p>When no values have been added, the result is zero.
216      *
217      * @return sum of squares of all values.
218      */
219     @Override
220     public BigInteger getAsBigInteger() {
221         return sumSq.toBigInteger();
222     }
223 
224     @Override
225     public LongSumOfSquares combine(LongSumOfSquares other) {
226         sumSq.add(other.sumSq);
227         return this;
228     }
229 }