in commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/FastLoadedDiceRollerDiscreteSampler.java [439:468]
private static long sum(long[] frequencies) {
// Validate
if (frequencies == null || frequencies.length == 0) {
throw new IllegalArgumentException("frequencies must contain at least 1 value");
}
// Sum the values.
// Combine all the sign bits in the observations and the intermediate sum in a flag.
long m = 0;
long signFlag = 0;
for (final long o : frequencies) {
m += o;
signFlag |= o | m;
}
// Check for a sign-bit.
if (signFlag < 0) {
// One or more observations were negative, or the sum overflowed.
for (final long o : frequencies) {
if (o < 0) {
throw new IllegalArgumentException("frequencies must contain positive values: " + o);
}
}
throw new IllegalArgumentException("Overflow when summing frequencies");
}
if (m == 0) {
throw new IllegalArgumentException("Sum of frequencies is zero");
}
return m;
}