Class FirstMoment
- All Implemented Interfaces:
DoubleConsumer
- Direct Known Subclasses:
SumOfSquaredDeviations
mean = sum(x_i) / n
To limit numeric errors, the value of the statistic is computed using the following recursive updating algorithm:
- Initialize
m =the first value - For each additional value, update using
m = m + (new value - m) / (number of observations)
Returns NaN if the dataset is empty. Note that
NaN may also be returned if the input includes NaN and / or infinite
values of opposite sign.
Supports up to 263 (exclusive) observations. This implementation does not check for overflow of the count.
Note that this implementation is not synchronized. If
multiple threads access an instance of this class concurrently, and at least
one of the threads invokes the accept or
combine method, it must be synchronized externally.
However, it is safe to use accept
and combine
as accumulator and combiner functions of
Collector on a parallel stream,
because the parallel implementation of Stream.collect()
provides the necessary partitioning, isolation, and merging of results for
safe and efficient parallel execution.
References:
- Chan, Golub, Levesque (1983) Algorithms for Computing the Sample Variance. American Statistician, vol. 37, no. 3, pp. 242-247.
- Ling (1974) Comparison of Several Algorithms for Computing Sample Means and Variances. Journal of the American Statistical Association, Vol. 69, No. 348, pp. 859-866.
- Since:
- 1.1
-
Field Summary
FieldsModifier and TypeFieldDescriptionprotected doubleHalf the deviation of most recently added value from the previous first moment.private static final doubleThe downscale constant.private doubleFirst moment of values that have been added.protected longCount of values that have been added.protected doubleHalf the deviation of most recently added value from the previous first moment, normalized by current sample size.private doubleRunning sum of values seen so far.private static final doubleThe rescale constant. -
Constructor Summary
ConstructorsConstructorDescriptionCreate an instance.FirstMoment(double m1, long n) Create an instance with the given first moment.FirstMoment(FirstMoment source) Copy constructor. -
Method Summary
Modifier and TypeMethodDescriptionvoidaccept(double value) Updates the state of the statistic to reflect the addition ofvalue.private static doublecombine(double m1, double m2, long n1, long n2) Combine the moments.(package private) FirstMomentcombine(FirstMoment other) Combines the state of anotherFirstMomentinto this one.private static doublecomputeNonFiniteValue(double[] values, int from, int to) Compute the result in the event of non-finite values.private static FirstMomentcreate(double[] values, int from, int to) Creates the first moment using a rolling algorithm.(package private) static FirstMomentcreateFromRange(org.apache.commons.numbers.core.Sum sum, double[] values, int from, int to) Creates the first moment.(package private) doubleGets the first moment of all input values.(package private) doubleGets the difference of the first moment betweenthismoment and theothermoment.(package private) doubleGets the half the difference of the first moment betweenthismoment and theothermoment.(package private) static FirstMomentof(double... values) Returns an instance populated using the inputvalues.(package private) static FirstMomentofRange(double[] values, int from, int to) Returns an instance populated using the specified range ofvalues.Methods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface DoubleConsumer
andThen
-
Field Details
-
DOWNSCALE
private static final double DOWNSCALEThe downscale constant. Used to avoid overflow for all finite input.- See Also:
-
RESCALE
private static final double RESCALEThe rescale constant.- See Also:
-
n
protected long nCount of values that have been added. -
dev
protected double devHalf the deviation of most recently added value from the previous first moment. Retained to prevent repeated computation in higher order moments.Note: This is (x - m1) / 2. It is computed as a half value to prevent overflow when computing for any finite value x and m.
This value is not used in the
combine(FirstMoment)method. -
nDev
protected double nDevHalf the deviation of most recently added value from the previous first moment, normalized by current sample size. Retained to prevent repeated computation in higher order moments.Note: This is (x - m1) / 2n. It is computed as a half value to prevent overflow when computing for any finite value x and m. Note: This value is not used in the
combine(FirstMoment)method. -
m1
private double m1First moment of values that have been added. This is stored as a half value to prevent overflow for any finite input. Benchmarks show this has negligible performance impact. -
nonFiniteValue
private double nonFiniteValueRunning sum of values seen so far. This is not used in the computation of mean. Used as a return value for first moment when it is non-finite.
-
-
Constructor Details
-
FirstMoment
FirstMoment()Create an instance. -
FirstMoment
-
FirstMoment
FirstMoment(double m1, long n) Create an instance with the given first moment.This constructor is used when creating the moment from a finite sum of values.
- Parameters:
m1- First moment.n- Count of values.
-
-
Method Details
-
of
Returns an instance populated using the inputvalues.Note:
FirstMomentcomputed usingaccept(double)may be different from this instance.- Parameters:
values- Values.- Returns:
FirstMomentinstance.
-
ofRange
Returns an instance populated using the specified range ofvalues.Note:
FirstMomentcomputed usingaccept(double)may be different from this instance.Warning: No range checks are performed.
- Parameters:
values- Values.from- Inclusive start of the range.to- Exclusive end of the range.- Returns:
FirstMomentinstance.- Throws:
IndexOutOfBoundsException- if the sub-range is out of bounds- Since:
- 1.2
-
createFromRange
static FirstMoment createFromRange(org.apache.commons.numbers.core.Sum sum, double[] values, int from, int to) Creates the first moment.Uses the provided
sumif finite; otherwise reverts to using the rolling moment to protect from overflow and adds a second pass correction term.This method is used by
DoubleStatisticsusing a sum that can be reused for theSumstatistic.Warning: No range checks are performed.
- Parameters:
sum- Sum of the values.values- Values.from- Inclusive start of the range.to- Exclusive end of the range.- Returns:
FirstMomentinstance.
-
create
Creates the first moment using a rolling algorithm.This duplicates the algorithm in the
accept(double)method with optimisations due to the processing of an entire array:- Avoid updating (unused) class level working variables.
- Only computing the non-finite value if required.
- Parameters:
values- Values.from- Inclusive start of the range.to- Exclusive end of the range.- Returns:
- the first moment
-
computeNonFiniteValue
private static double computeNonFiniteValue(double[] values, int from, int to) Compute the result in the event of non-finite values.- Parameters:
values- Values.from- Inclusive start of the range.to- Exclusive end of the range.- Returns:
- the non-finite result
-
accept
public void accept(double value) Updates the state of the statistic to reflect the addition ofvalue.- Specified by:
acceptin interfaceDoubleConsumer- Parameters:
value- Value.
-
getFirstMoment
double getFirstMoment()Gets the first moment of all input values.When no values have been added, the result is
NaN.- Returns:
First momentof all values, if it is finite;+/-Infinity, if infinities of the same sign have been encountered;NaNotherwise.
-
combine
Combines the state of anotherFirstMomentinto this one.- Parameters:
other- AnotherFirstMomentto be combined.- Returns:
thisinstance after combiningother.
-
combine
private static double combine(double m1, double m2, long n1, long n2) Combine the moments. This method is used to enforce symmetry. It assumes that the two sizes are not identical, and at least one size is non-zero.- Parameters:
m1- Moment 1.m2- Moment 2.n1- Size of sample 1.n2- Size of sample 2.- Returns:
- the combined first moment
-
getFirstMomentDifference
Gets the difference of the first moment betweenthismoment and theothermoment. This is provided for sub-classes.- Parameters:
other- Other moment.- Returns:
- the difference
-
getFirstMomentHalfDifference
Gets the half the difference of the first moment betweenthismoment and theothermoment. This is provided for sub-classes.- Parameters:
other- Other moment.- Returns:
- the difference
-