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     * @param values Values.
094     * @return {@code LongSumOfSquares} instance.
095     */
096    public static LongSumOfSquares of(long... values) {
097        final UInt192 ss = UInt192.create();
098        for (final long x : values) {
099            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}