IntSum.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 available values.
  21.  *
  22.  * <ul>
  23.  *   <li>The result is zero if no values are added.
  24.  * </ul>
  25.  *
  26.  * <p>This class uses an exact integer sum. The exact sum is
  27.  * returned using {@link #getAsBigInteger()}. Methods that return {@code int} or
  28.  * {@code long} primitives will raise an exception if the result overflows.
  29.  * The {@code long} value is safe up to the maximum array length for any input
  30.  * {@code int[]} data. The {@code long} value can overflow when instances are combined.
  31.  *
  32.  * <p>Note that the implementation does not use {@code BigInteger} arithmetic; for
  33.  * performance the sum is computed using primitives to create a signed 128-bit integer.
  34.  * Support is provided for at least 2<sup>63</sup> observations.
  35.  *
  36.  * <p>This class is designed to work with (though does not require)
  37.  * {@linkplain java.util.stream streams}.
  38.  *
  39.  * <p><strong>This implementation is not thread safe.</strong>
  40.  * If multiple threads access an instance of this class concurrently,
  41.  * and at least one of the threads invokes the {@link java.util.function.IntConsumer#accept(int) accept} or
  42.  * {@link StatisticAccumulator#combine(StatisticResult) combine} method, it must be synchronized externally.
  43.  *
  44.  * <p>However, it is safe to use {@link java.util.function.IntConsumer#accept(int) accept}
  45.  * and {@link StatisticAccumulator#combine(StatisticResult) combine}
  46.  * as {@code accumulator} and {@code combiner} functions of
  47.  * {@link java.util.stream.Collector Collector} on a parallel stream,
  48.  * because the parallel implementation of {@link java.util.stream.Stream#collect Stream.collect()}
  49.  * provides the necessary partitioning, isolation, and merging of results for
  50.  * safe and efficient parallel execution.
  51.  *
  52.  * @since 1.1
  53.  */
  54. public final class IntSum implements IntStatistic, StatisticAccumulator<IntSum> {
  55.     /** Sum of the values. */
  56.     private final Int128 sum;

  57.     /**
  58.      * Create an instance.
  59.      */
  60.     private IntSum() {
  61.         this(Int128.create());
  62.     }

  63.     /**
  64.      * Create an instance.
  65.      *
  66.      * @param sum Sum of the values.
  67.      */
  68.     private IntSum(Int128 sum) {
  69.         this.sum = sum;
  70.     }

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

  81.     /**
  82.      * Returns an instance populated using the input {@code values}.
  83.      *
  84.      * <p>When the input is an empty array, the result is zero.
  85.      *
  86.      * <p>The {@link #getAsLong()} result is valid for any input {@code int[]} length;
  87.      * the {@link #getAsInt()} result may overflow.
  88.      *
  89.      * @param values Values.
  90.      * @return {@code IntSum} instance.
  91.      */
  92.     public static IntSum of(int... values) {
  93.         // Sum of an array cannot exceed a 64-bit long
  94.         long s = 0;
  95.         for (final int x : values) {
  96.             s += x;
  97.         }
  98.         // Convert
  99.         return new IntSum(Int128.of(s));
  100.     }

  101.     /**
  102.      * Gets the sum.
  103.      *
  104.      * <p>This is package private for use in {@link IntStatistics}.
  105.      *
  106.      * @return the sum
  107.      */
  108.     Int128 getSum() {
  109.         return sum;
  110.     }

  111.     /**
  112.      * Updates the state of the statistic to reflect the addition of {@code value}.
  113.      *
  114.      * @param value Value.
  115.      */
  116.     @Override
  117.     public void accept(int value) {
  118.         sum.add(value);
  119.     }

  120.     /**
  121.      * Gets the sum of all input values.
  122.      *
  123.      * <p>When no values have been added, the result is zero.
  124.      *
  125.      * <p>Warning: This will raise an {@link ArithmeticException}
  126.      * if the result is not within the range {@code [-2^31, 2^31)}.
  127.      *
  128.      * @return sum of all values.
  129.      * @throws ArithmeticException if the {@code result} overflows an {@code int}
  130.      * @see #getAsBigInteger()
  131.      */
  132.     @Override
  133.     public int getAsInt() {
  134.         return sum.toIntExact();
  135.     }

  136.     /**
  137.      * Gets the sum of all input values.
  138.      *
  139.      * <p>When no values have been added, the result is zero.
  140.      *
  141.      * <p>Warning: This will raise an {@link ArithmeticException}
  142.      * if the result is not within the range {@code [-2^63, 2^63)}.
  143.      *
  144.      * @return sum of all values.
  145.      * @throws ArithmeticException if the {@code result} overflows a {@code long}
  146.      * @see #getAsBigInteger()
  147.      */
  148.     @Override
  149.     public long getAsLong() {
  150.         return sum.toLongExact();
  151.     }

  152.     /**
  153.      * Gets the sum of all input values.
  154.      *
  155.      * <p>When no values have been added, the result is zero.
  156.      *
  157.      * <p>Note that this conversion can lose information about the precision of the
  158.      * {@code BigInteger} value.
  159.      *
  160.      * @return sum of all values.
  161.      * @see #getAsBigInteger()
  162.      */
  163.     @Override
  164.     public double getAsDouble() {
  165.         return sum.toDouble();
  166.     }

  167.     /**
  168.      * Gets the sum of all input values.
  169.      *
  170.      * <p>When no values have been added, the result is zero.
  171.      *
  172.      * @return sum of all values.
  173.      */
  174.     @Override
  175.     public BigInteger getAsBigInteger() {
  176.         return sum.toBigInteger();
  177.     }

  178.     @Override
  179.     public IntSum combine(IntSum other) {
  180.         sum.add(other.sum);
  181.         return this;
  182.     }
  183. }