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 squares of the available values. Uses the following definition: 023 * 024 * <p>\[ \sum_{i=1}^n x_i^2 \] 025 * 026 * <p>where \( n \) is the number of samples. 027 * 028 * <ul> 029 * <li>The result is zero if no values are observed. 030 * </ul> 031 * 032 * <p>The implementation uses an exact integer sum to compute the sum of squared values. 033 * The exact sum is returned using {@link #getAsBigInteger()}. Methods that return {@code int} or 034 * {@code long} primitives will raise an exception if the result overflows. 035 * 036 * <p>Note that the implementation does not use {@code BigInteger} arithmetic; for 037 * performance the sum is computed using primitives to create an unsigned 128-bit integer. 038 * Support is provided for at least 2<sup>63</sup> observations. 039 * 040 * <p>This class is designed to work with (though does not require) 041 * {@linkplain java.util.stream streams}. 042 * 043 * <p><strong>This implementation is not thread safe.</strong> 044 * If multiple threads access an instance of this class concurrently, 045 * and at least one of the threads invokes the {@link java.util.function.IntConsumer#accept(int) accept} or 046 * {@link StatisticAccumulator#combine(StatisticResult) combine} method, it must be synchronized externally. 047 * 048 * <p>However, it is safe to use {@link java.util.function.IntConsumer#accept(int) accept} 049 * and {@link StatisticAccumulator#combine(StatisticResult) combine} 050 * as {@code accumulator} and {@code combiner} functions of 051 * {@link java.util.stream.Collector Collector} on a parallel stream, 052 * because the parallel implementation of {@link java.util.stream.Stream#collect Stream.collect()} 053 * provides the necessary partitioning, isolation, and merging of results for 054 * safe and efficient parallel execution. 055 * 056 * @since 1.1 057 */ 058public final class IntSumOfSquares implements IntStatistic, StatisticAccumulator<IntSumOfSquares> { 059 /** Small array sample size. 060 * Used to avoid computing with UInt96 then converting to UInt128. */ 061 private static final int SMALL_SAMPLE = 10; 062 063 /** Sum of the squared values. */ 064 private final UInt128 sumSq; 065 066 /** 067 * Create an instance. 068 */ 069 private IntSumOfSquares() { 070 this(UInt128.create()); 071 } 072 073 /** 074 * Create an instance. 075 * 076 * @param sumSq Sum of the squared values. 077 */ 078 private IntSumOfSquares(UInt128 sumSq) { 079 this.sumSq = sumSq; 080 } 081 082 /** 083 * Creates an instance. 084 * 085 * <p>The initial result is zero. 086 * 087 * @return {@code IntSumOfSquares} instance. 088 */ 089 public static IntSumOfSquares create() { 090 return new IntSumOfSquares(); 091 } 092 093 /** 094 * Returns an instance populated using the input {@code values}. 095 * 096 * @param values Values. 097 * @return {@code IntSumOfSquares} instance. 098 */ 099 public static IntSumOfSquares of(int... values) { 100 // Small arrays can be processed using the object 101 if (values.length < SMALL_SAMPLE) { 102 final IntSumOfSquares stat = new IntSumOfSquares(); 103 for (final int x : values) { 104 stat.accept(x); 105 } 106 return stat; 107 } 108 109 // Arrays can be processed using specialised counts knowing the maximum limit 110 // for an array is 2^31 values. 111 final UInt96 ss = UInt96.create(); 112 // Process pairs as we know two maximum value int^2 will not overflow 113 // an unsigned long. 114 final int end = values.length & ~0x1; 115 for (int i = 0; i < end; i += 2) { 116 final long x = values[i]; 117 final long y = values[i + 1]; 118 ss.addPositive(x * x + y * y); 119 } 120 if (end < values.length) { 121 final long x = values[end]; 122 ss.addPositive(x * x); 123 } 124 125 // Convert 126 return new IntSumOfSquares(UInt128.of(ss)); 127 } 128 129 /** 130 * Gets the sum of squares. 131 * 132 * <p>This is package private for use in {@link IntStatistics}. 133 * 134 * @return the sum of squares 135 */ 136 UInt128 getSumOfSquares() { 137 return sumSq; 138 } 139 140 /** 141 * Updates the state of the statistic to reflect the addition of {@code value}. 142 * 143 * @param value Value. 144 */ 145 @Override 146 public void accept(int value) { 147 sumSq.addPositive((long) value * value); 148 } 149 150 /** 151 * Gets the sum of squares of all input values. 152 * 153 * <p>When no values have been added, the result is zero. 154 * 155 * <p>Warning: This will raise an {@link ArithmeticException} 156 * if the result is not within the range {@code [0, 2^31)}. 157 * 158 * @return sum of all values. 159 * @throws ArithmeticException if the {@code result} overflows an {@code int} 160 * @see #getAsBigInteger() 161 */ 162 @Override 163 public int getAsInt() { 164 return sumSq.toIntExact(); 165 } 166 167 /** 168 * Gets the sum of squares of all input values. 169 * 170 * <p>When no values have been added, the result is zero. 171 * 172 * <p>Warning: This will raise an {@link ArithmeticException} 173 * if the result is not within the range {@code [0, 2^63)}. 174 * 175 * @return sum of all values. 176 * @throws ArithmeticException if the {@code result} overflows a {@code long} 177 * @see #getAsBigInteger() 178 */ 179 @Override 180 public long getAsLong() { 181 return sumSq.toLongExact(); 182 } 183 184 /** 185 * Gets the sum of squares of all input values. 186 * 187 * <p>When no values have been added, the result is zero. 188 * 189 * <p>Note that this conversion can lose information about the precision of the 190 * {@code BigInteger} value. 191 * 192 * @return sum of squares of all values. 193 * @see #getAsBigInteger() 194 */ 195 @Override 196 public double getAsDouble() { 197 return sumSq.toDouble(); 198 } 199 200 /** 201 * Gets the sum of squares of all input values. 202 * 203 * <p>When no values have been added, the result is zero. 204 * 205 * @return sum of squares of all values. 206 */ 207 @Override 208 public BigInteger getAsBigInteger() { 209 return sumSq.toBigInteger(); 210 } 211 212 @Override 213 public IntSumOfSquares combine(IntSumOfSquares other) { 214 sumSq.add(other.sumSq); 215 return this; 216 } 217}