LongSumOfSquares.java

  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. import java.math.BigInteger;

  19. /**
  20.  * Returns the sum of the squares of the available values. Uses the following definition:
  21.  *
  22.  * <p>\[ \sum_{i=1}^n x_i^2 \]
  23.  *
  24.  * <p>where \( n \) is the number of samples.
  25.  *
  26.  * <ul>
  27.  *   <li>The result is zero if no values are observed.
  28.  * </ul>
  29.  *
  30.  * <p>The implementation uses an exact integer sum to compute the sum of squared values.
  31.  * The exact sum is returned using {@link #getAsBigInteger()}. Methods that return {@code int} or
  32.  * {@code long} primitives will raise an exception if the result overflows.
  33.  *
  34.  * <p>Note that the implementation does not use {@code BigInteger} arithmetic; for
  35.  * performance the sum is computed using primitives to create an unsigned 192-bit integer.
  36.  * Support is provided for at least 2<sup>63</sup> observations.
  37.  *
  38.  * <p>This class is designed to work with (though does not require)
  39.  * {@linkplain java.util.stream streams}.
  40.  *
  41.  * <p><strong>This implementation is not thread safe.</strong>
  42.  * If multiple threads access an instance of this class concurrently,
  43.  * and at least one of the threads invokes the {@link java.util.function.IntConsumer#accept(int) accept} or
  44.  * {@link StatisticAccumulator#combine(StatisticResult) combine} method, it must be synchronized externally.
  45.  *
  46.  * <p>However, it is safe to use {@link java.util.function.IntConsumer#accept(int) accept}
  47.  * and {@link StatisticAccumulator#combine(StatisticResult) combine}
  48.  * as {@code accumulator} and {@code combiner} functions of
  49.  * {@link java.util.stream.Collector Collector} on a parallel stream,
  50.  * because the parallel implementation of {@link java.util.stream.Stream#collect Stream.collect()}
  51.  * provides the necessary partitioning, isolation, and merging of results for
  52.  * safe and efficient parallel execution.
  53.  *
  54.  * @since 1.1
  55.  */
  56. public final class LongSumOfSquares implements LongStatistic, StatisticAccumulator<LongSumOfSquares> {

  57.     /** Sum of the squared values. */
  58.     private final UInt192 sumSq;

  59.     /**
  60.      * Create an instance.
  61.      */
  62.     private LongSumOfSquares() {
  63.         this(UInt192.create());
  64.     }

  65.     /**
  66.      * Create an instance.
  67.      *
  68.      * @param sumSq Sum of the squared values.
  69.      */
  70.     private LongSumOfSquares(UInt192 sumSq) {
  71.         this.sumSq = sumSq;
  72.     }

  73.     /**
  74.      * Creates an instance.
  75.      *
  76.      * <p>The initial result is zero.
  77.      *
  78.      * @return {@code LongSumOfSquares} instance.
  79.      */
  80.     public static LongSumOfSquares create() {
  81.         return new LongSumOfSquares();
  82.     }

  83.     /**
  84.      * Returns an instance populated using the input {@code values}.
  85.      *
  86.      * @param values Values.
  87.      * @return {@code LongSumOfSquares} instance.
  88.      */
  89.     public static LongSumOfSquares of(long... values) {
  90.         final UInt192 ss = UInt192.create();
  91.         for (final long x : values) {
  92.             ss.addSquare(x);
  93.         }
  94.         return new LongSumOfSquares(ss);
  95.     }

  96.     /**
  97.      * Gets the sum of squares.
  98.      *
  99.      * <p>This is package private for use in {@link IntStatistics}.
  100.      *
  101.      * @return the sum of squares
  102.      */
  103.     UInt192 getSumOfSquares() {
  104.         return sumSq;
  105.     }

  106.     /**
  107.      * Updates the state of the statistic to reflect the addition of {@code value}.
  108.      *
  109.      * @param value Value.
  110.      */
  111.     @Override
  112.     public void accept(long value) {
  113.         sumSq.addSquare(value);
  114.     }

  115.     /**
  116.      * Gets the sum of squares of all input values.
  117.      *
  118.      * <p>When no values have been added, the result is zero.
  119.      *
  120.      * <p>Warning: This will raise an {@link ArithmeticException}
  121.      * if the result is not within the range {@code [0, 2^31)}.
  122.      *
  123.      * @return sum of all values.
  124.      * @throws ArithmeticException if the {@code result} overflows an {@code int}
  125.      * @see #getAsBigInteger()
  126.      */
  127.     @Override
  128.     public int getAsInt() {
  129.         return sumSq.toIntExact();
  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.      * <p>Warning: This will raise an {@link ArithmeticException}
  137.      * if the result is not within the range {@code [0, 2^63)}.
  138.      *
  139.      * @return sum of all values.
  140.      * @throws ArithmeticException if the {@code result} overflows a {@code long}
  141.      * @see #getAsBigInteger()
  142.      */
  143.     @Override
  144.     public long getAsLong() {
  145.         return sumSq.toLongExact();
  146.     }

  147.     /**
  148.      * Gets the sum of squares of all input values.
  149.      *
  150.      * <p>When no values have been added, the result is zero.
  151.      *
  152.      * <p>Note that this conversion can lose information about the precision of the
  153.      * {@code BigInteger} value.
  154.      *
  155.      * @return sum of squares of all values.
  156.      * @see #getAsBigInteger()
  157.      */
  158.     @Override
  159.     public double getAsDouble() {
  160.         return sumSq.toDouble();
  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.      * @return sum of squares of all values.
  168.      */
  169.     @Override
  170.     public BigInteger getAsBigInteger() {
  171.         return sumSq.toBigInteger();
  172.     }

  173.     @Override
  174.     public LongSumOfSquares combine(LongSumOfSquares other) {
  175.         sumSq.add(other.sumSq);
  176.         return this;
  177.     }
  178. }