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