LongSum.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.  *
  30.  * <p>Note that the implementation does not use {@code BigInteger} arithmetic; for
  31.  * performance the sum is computed using primitives to create a signed 128-bit integer.
  32.  * Support is provided for at least 2<sup>63</sup> observations.
  33.  *
  34.  * <p>This class is designed to work with (though does not require)
  35.  * {@linkplain java.util.stream streams}.
  36.  *
  37.  * <p><strong>This implementation is not thread safe.</strong>
  38.  * If multiple threads access an instance of this class concurrently,
  39.  * and at least one of the threads invokes the {@link java.util.function.LongConsumer#accept(long) accept} or
  40.  * {@link StatisticAccumulator#combine(StatisticResult) combine} method, it must be synchronized externally.
  41.  *
  42.  * <p>However, it is safe to use {@link java.util.function.LongConsumer#accept(long) accept}
  43.  * and {@link StatisticAccumulator#combine(StatisticResult) combine}
  44.  * as {@code accumulator} and {@code combiner} functions of
  45.  * {@link java.util.stream.Collector Collector} on a parallel stream,
  46.  * because the parallel implementation of {@link java.util.stream.Stream#collect Stream.collect()}
  47.  * provides the necessary partitioning, isolation, and merging of results for
  48.  * safe and efficient parallel execution.
  49.  *
  50.  * @since 1.1
  51.  */
  52. public final class LongSum implements LongStatistic, StatisticAccumulator<LongSum> {
  53.     /** Sum of the values. */
  54.     private final Int128 sum;

  55.     /**
  56.      * Create an instance.
  57.      */
  58.     private LongSum() {
  59.         this(Int128.create());
  60.     }

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

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

  79.     /**
  80.      * Returns an instance populated using the input {@code values}.
  81.      *
  82.      * <p>When the input is an empty array, the result is zero.
  83.      *
  84.      * @param values Values.
  85.      * @return {@code LongSum} instance.
  86.      */
  87.     public static LongSum of(long... values) {
  88.         final Int128 s = Int128.create();
  89.         for (final long x : values) {
  90.             s.add(x);
  91.         }
  92.         return new LongSum(s);
  93.     }

  94.     /**
  95.      * Returns an instance populated using the specified range of {@code values}.
  96.      *
  97.      * <p>When the range is empty, the result is zero.
  98.      *
  99.      * @param values Values.
  100.      * @param from Inclusive start of the range.
  101.      * @param to Exclusive end of the range.
  102.      * @return {@code LongSum} instance.
  103.      * @throws IndexOutOfBoundsException if the sub-range is out of bounds
  104.      * @since 1.2
  105.      */
  106.     public static LongSum ofRange(long[] values, int from, int to) {
  107.         Statistics.checkFromToIndex(from, to, values.length);
  108.         return createFromRange(values, from, to);
  109.     }

  110.     /**
  111.      * Create an instance using the specified range of {@code values}.
  112.      *
  113.      * <p>Warning: No range checks are performed.
  114.      *
  115.      * @param values Values.
  116.      * @param from Inclusive start of the range.
  117.      * @param to Exclusive end of the range.
  118.      * @return {@code LongSum} instance.
  119.      */
  120.     static LongSum createFromRange(long[] values, int from, int to) {
  121.         final Int128 s = Int128.create();
  122.         for (int i = from; i < to; i++) {
  123.             s.add(values[i]);
  124.         }
  125.         return new LongSum(s);
  126.     }

  127.     /**
  128.      * Gets the sum.
  129.      *
  130.      * <p>This is package private for use in {@link LongStatistics}.
  131.      *
  132.      * @return the sum
  133.      */
  134.     Int128 getSum() {
  135.         return sum;
  136.     }

  137.     /**
  138.      * Updates the state of the statistic to reflect the addition of {@code value}.
  139.      *
  140.      * @param value Value.
  141.      */
  142.     @Override
  143.     public void accept(long value) {
  144.         sum.add(value);
  145.     }

  146.     /**
  147.      * Gets the sum of all input values.
  148.      *
  149.      * <p>When no values have been added, the result is zero.
  150.      *
  151.      * <p>Warning: This will raise an {@link ArithmeticException}
  152.      * if the result is not within the range {@code [-2^31, 2^31)}.
  153.      *
  154.      * @return sum of all values.
  155.      * @throws ArithmeticException if the {@code result} overflows an {@code int}
  156.      * @see #getAsBigInteger()
  157.      */
  158.     @Override
  159.     public int getAsInt() {
  160.         return sum.toIntExact();
  161.     }

  162.     /**
  163.      * Gets the sum 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 [-2^63, 2^63)}.
  169.      *
  170.      * @return sum of all values.
  171.      * @throws ArithmeticException if the {@code result} overflows a {@code long}
  172.      * @see #getAsBigInteger()
  173.      */
  174.     @Override
  175.     public long getAsLong() {
  176.         return sum.toLongExact();
  177.     }

  178.     /**
  179.      * Gets the sum of all input values.
  180.      *
  181.      * <p>When no values have been added, the result is zero.
  182.      *
  183.      * <p>Note that this conversion can lose information about the precision of the
  184.      * {@code BigInteger} value.
  185.      *
  186.      * @return sum of all values.
  187.      * @see #getAsBigInteger()
  188.      */
  189.     @Override
  190.     public double getAsDouble() {
  191.         return sum.toDouble();
  192.     }

  193.     /**
  194.      * Gets the sum of all input values.
  195.      *
  196.      * <p>When no values have been added, the result is zero.
  197.      *
  198.      * @return sum of all values.
  199.      */
  200.     @Override
  201.     public BigInteger getAsBigInteger() {
  202.         return sum.toBigInteger();
  203.     }

  204.     @Override
  205.     public LongSum combine(LongSum other) {
  206.         sum.add(other.sum);
  207.         return this;
  208.     }
  209. }