Java Utililty Methods Number Sum

List of utility methods to do Number Sum

Description

The list of methods to do Number Sum are organized into topic(s).

Method

doublesumAsDouble(Iterable values)
Calculate the total sum of the numbers in the specified collection.
double total = 0;
for (Number value : values) {
    total += value.doubleValue();
return total;
floatSumDiffErr(float Term1Err, float Term2Err)
Calculate the error in a sum or difference, based on the error in the two terms
return (float) Math.sqrt(Term1Err * Term1Err + Term2Err * Term2Err);
intsumDigits(String number)
Sums the digits of a natural number represented as a String.
return number.chars().map(aChar -> Character.getNumericValue(aChar)).sum();
intsumDivisors(int n)
sum Divisors
int sum = 0;
for (int i = 1; i < n; i++)
    if (n % i == 0)
        sum += i;
return sum;
doublesumError(long samples, long count, double m2, double mean)
Computes the standard deviation for the random variable S = sum(1 / p * X * Bern(p))

Derivation:
 Var(S) = Var(sum(1 / p * X * Bern(p))) = sum(Var(1 / p * X * Bern(p)))                                                           [Bienayme formula] = n * Var(1 / p * X * Bern(p))                                                            [X * Bern(p) are iid] = n * 1 / p^2 * Var(X * Bern(p))                                                          [1 / p is constant] = n * 1 / p^2 * (Var(X) * Var(Bern(p)) + E(X)^2 * Var(Bern(p)) + Var(X) * E(Bern(p))^2    [Product of independent variables] = n * 1 / p^2 * (Var(X) * p(1 - p) + E(X)^2 * p(1 - p) + Var(X) * p^2)                    [Variance of a Bernoulli distribution] = n * 1 / p * (Var(X) + E(X)^2 * (1 - p)) = samples / p^2 * (Var(X) + E(X)^2 * (1 - p))                                             [samples = n * p, since it's only the observed rows] 
Therefore Stddev(S) = 1 / p * sqrt(samples * (variance + mean^2 * (1 - p)))
if (count == 0) {
    return Double.POSITIVE_INFINITY;
double p = samples / (double) count;
double variance = m2 / samples;
double error = 1 / p * Math.sqrt(samples * (variance + mean * mean * (1 - p)));
return conservativeError(error, p, samples);
longsumFirstIntegers(final long i)
Compute the sum of the i first integers.
return ((i - 1L) * i) >> 1;
longsumFirstN(long n)
sum First N
return (n * (n + 1)) / 2;
longsumFirstNDivisibleByM(long n, long m)
sum First N Divisible By M
return sumFirstNDivisibleByM(n, m, true);
intsumFromNtoM(int n, int m)
Returns the sum from n to m (Ex: n = 1, m = 3 => 1 + 2 + 3 = 6)
return Math.abs(m - n + 1) * (m + n) / 2;
booleansumHadOverflow(long a, long b, long sum)
sum Had Overflow
return ((a ^ sum) & (b ^ sum)) < 0;