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
019/**
020 * Returns the sum of the squares of the available values. Uses the following definition:
021 *
022 * <p>\[ \sum_{i=1}^n x_i^2 \]
023 *
024 * <p>where \( n \) is the number of samples.
025 *
026 * <ul>
027 *   <li>The result is zero if no values are observed.
028 *   <li>The result is {@code NaN} if any of the values is {@code NaN}.
029 *   <li>The result is {@code +infinity} if any of the values is {@code infinity},
030 *       or the sum overflows.
031 * </ul>
032 *
033 * <p>This class is designed to work with (though does not require)
034 * {@linkplain java.util.stream streams}.
035 *
036 * <p><strong>This instance is not thread safe.</strong>
037 * If multiple threads access an instance of this class concurrently,
038 * and at least one of the threads invokes the {@link java.util.function.DoubleConsumer#accept(double) accept} or
039 * {@link StatisticAccumulator#combine(StatisticResult) combine} method, it must be synchronized externally.
040 *
041 * <p>However, it is safe to use {@link java.util.function.DoubleConsumer#accept(double) accept}
042 * and {@link StatisticAccumulator#combine(StatisticResult) combine}
043 * as {@code accumulator} and {@code combiner} functions of
044 * {@link java.util.stream.Collector Collector} on a parallel stream,
045 * because the parallel instance of {@link java.util.stream.Stream#collect Stream.collect()}
046 * provides the necessary partitioning, isolation, and merging of results for
047 * safe and efficient parallel execution.
048 *
049 * @since 1.1
050 */
051public final class SumOfSquares implements DoubleStatistic, StatisticAccumulator<SumOfSquares> {
052
053    /** Sum of squares of all values. */
054    private double ss;
055
056    /**
057     * Create an instance.
058     */
059    private SumOfSquares() {
060        // No-op
061    }
062
063    /**
064     * Creates an instance.
065     *
066     * <p>The initial result is zero.
067     *
068     * @return {@code SumOfSquares} instance.
069     */
070    public static SumOfSquares create() {
071        return new SumOfSquares();
072    }
073
074    /**
075     * Returns an instance populated using the input {@code values}.
076     *
077     * <p>The result is {@code NaN} if any of the values is {@code NaN}.
078     *
079     * <p>When the input is an empty array, the result is zero.
080     *
081     * @param values Values.
082     * @return {@code SumOfSquares} instance.
083     */
084    public static SumOfSquares of(double... values) {
085        return Statistics.add(new SumOfSquares(), values);
086    }
087
088    /**
089     * Returns an instance populated using the specified range of {@code values}.
090     *
091     * <p>The result is {@code NaN} if any of the values is {@code NaN}.
092     *
093     * <p>When the range is empty, the result is zero.
094     *
095     * @param values Values.
096     * @param from Inclusive start of the range.
097     * @param to Exclusive end of the range.
098     * @return {@code SumOfSquares} instance.
099     * @throws IndexOutOfBoundsException if the sub-range is out of bounds
100     * @since 1.2
101     */
102    public static SumOfSquares ofRange(double[] values, int from, int to) {
103        Statistics.checkFromToIndex(from, to, values.length);
104        return createFromRange(values, from, to);
105    }
106
107    /**
108     * Create an instance using the specified range of {@code values}.
109     *
110     * <p>Warning: No range checks are performed.
111     *
112     * @param values Values.
113     * @param from Inclusive start of the range.
114     * @param to Exclusive end of the range.
115     * @return {@code SumOfSquares} instance.
116     */
117    static SumOfSquares createFromRange(double[] values, int from, int to) {
118        return Statistics.add(new SumOfSquares(), values, from, to);
119    }
120
121    /**
122     * Updates the state of the statistic to reflect the addition of {@code value}.
123     *
124     * @param value Value.
125     */
126    @Override
127    public void accept(double value) {
128        ss += value * value;
129    }
130
131    /**
132     * Gets the sum of squares of all input values.
133     *
134     * <p>When no values have been added, the result is zero.
135     *
136     * @return sum of squares of all values.
137     */
138    @Override
139    public double getAsDouble() {
140        return ss;
141    }
142
143    @Override
144    public SumOfSquares combine(SumOfSquares other) {
145        ss += other.ss;
146        return this;
147    }
148}