001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.statistics.descriptive;
018
019import java.math.BigInteger;
020
021/**
022 * Returns the sum of the squares of the available values. Uses the following definition:
023 *
024 * <p>\[ \sum_{i=1}^n x_i^2 \]
025 *
026 * <p>where \( n \) is the number of samples.
027 *
028 * <ul>
029 *   <li>The result is zero if no values are observed.
030 * </ul>
031 *
032 * <p>The implementation uses an exact integer sum to compute the sum of squared values.
033 * The exact sum is returned using {@link #getAsBigInteger()}. Methods that return {@code int} or
034 * {@code long} primitives will raise an exception if the result overflows.
035 *
036 * <p>Note that the implementation does not use {@code BigInteger} arithmetic; for
037 * performance the sum is computed using primitives to create an unsigned 192-bit integer.
038 * Support is provided for at least 2<sup>63</sup> observations.
039 *
040 * <p>This class is designed to work with (though does not require)
041 * {@linkplain java.util.stream streams}.
042 *
043 * <p><strong>This implementation is not thread safe.</strong>
044 * If multiple threads access an instance of this class concurrently,
045 * and at least one of the threads invokes the {@link java.util.function.IntConsumer#accept(int) accept} or
046 * {@link StatisticAccumulator#combine(StatisticResult) combine} method, it must be synchronized externally.
047 *
048 * <p>However, it is safe to use {@link java.util.function.IntConsumer#accept(int) accept}
049 * and {@link StatisticAccumulator#combine(StatisticResult) combine}
050 * as {@code accumulator} and {@code combiner} functions of
051 * {@link java.util.stream.Collector Collector} on a parallel stream,
052 * because the parallel implementation of {@link java.util.stream.Stream#collect Stream.collect()}
053 * provides the necessary partitioning, isolation, and merging of results for
054 * safe and efficient parallel execution.
055 *
056 * @since 1.1
057 */
058public final class LongSumOfSquares implements LongStatistic, StatisticAccumulator<LongSumOfSquares> {
059
060    /** Sum of the squared values. */
061    private final UInt192 sumSq;
062
063    /**
064     * Create an instance.
065     */
066    private LongSumOfSquares() {
067        this(UInt192.create());
068    }
069
070    /**
071     * Create an instance.
072     *
073     * @param sumSq Sum of the squared values.
074     */
075    private LongSumOfSquares(UInt192 sumSq) {
076        this.sumSq = sumSq;
077    }
078
079    /**
080     * Creates an instance.
081     *
082     * <p>The initial result is zero.
083     *
084     * @return {@code LongSumOfSquares} instance.
085     */
086    public static LongSumOfSquares create() {
087        return new LongSumOfSquares();
088    }
089
090    /**
091     * Returns an instance populated using the input {@code values}.
092     *
093     * <p>When the input is an empty array, the result is zero.
094     *
095     * @param values Values.
096     * @return {@code LongSumOfSquares} instance.
097     */
098    public static LongSumOfSquares of(long... values) {
099        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}