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 available values. 023 * 024 * <ul> 025 * <li>The result is zero if no values are added. 026 * </ul> 027 * 028 * <p>This class uses an exact integer sum. The exact sum is 029 * returned using {@link #getAsBigInteger()}. Methods that return {@code int} or 030 * {@code long} primitives will raise an exception if the result overflows. 031 * The {@code long} value is safe up to the maximum array length for any input 032 * {@code int[]} data. The {@code long} value can overflow when instances are combined. 033 * 034 * <p>Note that the implementation does not use {@code BigInteger} arithmetic; for 035 * performance the sum is computed using primitives to create a signed 128-bit integer. 036 * Support is provided for at least 2<sup>63</sup> observations. 037 * 038 * <p>This class is designed to work with (though does not require) 039 * {@linkplain java.util.stream streams}. 040 * 041 * <p><strong>This implementation is not thread safe.</strong> 042 * If multiple threads access an instance of this class concurrently, 043 * and at least one of the threads invokes the {@link java.util.function.IntConsumer#accept(int) accept} or 044 * {@link StatisticAccumulator#combine(StatisticResult) combine} method, it must be synchronized externally. 045 * 046 * <p>However, it is safe to use {@link java.util.function.IntConsumer#accept(int) accept} 047 * and {@link StatisticAccumulator#combine(StatisticResult) combine} 048 * as {@code accumulator} and {@code combiner} functions of 049 * {@link java.util.stream.Collector Collector} on a parallel stream, 050 * because the parallel implementation of {@link java.util.stream.Stream#collect Stream.collect()} 051 * provides the necessary partitioning, isolation, and merging of results for 052 * safe and efficient parallel execution. 053 * 054 * @since 1.1 055 */ 056public final class IntSum implements IntStatistic, StatisticAccumulator<IntSum> { 057 /** Sum of the values. */ 058 private final Int128 sum; 059 060 /** 061 * Create an instance. 062 */ 063 private IntSum() { 064 this(Int128.create()); 065 } 066 067 /** 068 * Create an instance. 069 * 070 * @param sum Sum of the values. 071 */ 072 private IntSum(Int128 sum) { 073 this.sum = sum; 074 } 075 076 /** 077 * Creates an instance. 078 * 079 * <p>The initial result is zero. 080 * 081 * @return {@code IntSum} instance. 082 */ 083 public static IntSum create() { 084 return new IntSum(); 085 } 086 087 /** 088 * Returns an instance populated using the input {@code values}. 089 * 090 * <p>When the input is an empty array, the result is zero. 091 * 092 * <p>The {@link #getAsLong()} result is valid for any input {@code int[]} length; 093 * the {@link #getAsInt()} result may overflow. 094 * 095 * @param values Values. 096 * @return {@code IntSum} instance. 097 */ 098 public static IntSum of(int... values) { 099 // Sum of an array cannot exceed a 64-bit long 100 long s = 0; 101 for (final int x : values) { 102 s += x; 103 } 104 // Convert 105 return new IntSum(Int128.of(s)); 106 } 107 108 /** 109 * Returns an instance populated using the specified range of {@code values}. 110 * 111 * <p>When the range is empty, the result is zero. 112 * 113 * <p>The {@link #getAsLong()} result is valid for any range length; 114 * the {@link #getAsInt()} result may overflow. 115 * 116 * @param values Values. 117 * @param from Inclusive start of the range. 118 * @param to Exclusive end of the range. 119 * @return {@code IntSum} instance. 120 * @throws IndexOutOfBoundsException if the sub-range is out of bounds 121 * @since 1.2 122 */ 123 public static IntSum ofRange(int[] values, int from, int to) { 124 Statistics.checkFromToIndex(from, to, values.length); 125 return createFromRange(values, from, to); 126 } 127 128 /** 129 * Create an instance using the specified range of {@code values}. 130 * 131 * <p>Warning: No range checks are performed. 132 * 133 * @param values Values. 134 * @param from Inclusive start of the range. 135 * @param to Exclusive end of the range. 136 * @return {@code IntSum} instance. 137 */ 138 static IntSum createFromRange(int[] values, int from, int to) { 139 // Sum of an array cannot exceed a 64-bit long 140 long s = 0; 141 for (int i = from; i < to; i++) { 142 s += values[i]; 143 } 144 // Convert 145 return new IntSum(Int128.of(s)); 146 } 147 148 /** 149 * Gets the sum. 150 * 151 * <p>This is package private for use in {@link IntStatistics}. 152 * 153 * @return the sum 154 */ 155 Int128 getSum() { 156 return sum; 157 } 158 159 /** 160 * Updates the state of the statistic to reflect the addition of {@code value}. 161 * 162 * @param value Value. 163 */ 164 @Override 165 public void accept(int value) { 166 sum.add(value); 167 } 168 169 /** 170 * Gets the sum of all input values. 171 * 172 * <p>When no values have been added, the result is zero. 173 * 174 * <p>Warning: This will raise an {@link ArithmeticException} 175 * if the result is not within the range {@code [-2^31, 2^31)}. 176 * 177 * @return sum of all values. 178 * @throws ArithmeticException if the {@code result} overflows an {@code int} 179 * @see #getAsBigInteger() 180 */ 181 @Override 182 public int getAsInt() { 183 return sum.toIntExact(); 184 } 185 186 /** 187 * Gets the sum of all input values. 188 * 189 * <p>When no values have been added, the result is zero. 190 * 191 * <p>Warning: This will raise an {@link ArithmeticException} 192 * if the result is not within the range {@code [-2^63, 2^63)}. 193 * 194 * @return sum of all values. 195 * @throws ArithmeticException if the {@code result} overflows a {@code long} 196 * @see #getAsBigInteger() 197 */ 198 @Override 199 public long getAsLong() { 200 return sum.toLongExact(); 201 } 202 203 /** 204 * Gets the sum of all input values. 205 * 206 * <p>When no values have been added, the result is zero. 207 * 208 * <p>Note that this conversion can lose information about the precision of the 209 * {@code BigInteger} value. 210 * 211 * @return sum of all values. 212 * @see #getAsBigInteger() 213 */ 214 @Override 215 public double getAsDouble() { 216 return sum.toDouble(); 217 } 218 219 /** 220 * Gets the sum of all input values. 221 * 222 * <p>When no values have been added, the result is zero. 223 * 224 * @return sum of all values. 225 */ 226 @Override 227 public BigInteger getAsBigInteger() { 228 return sum.toBigInteger(); 229 } 230 231 @Override 232 public IntSum combine(IntSum other) { 233 sum.add(other.sum); 234 return this; 235 } 236}