You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by ah...@apache.org on 2025/03/21 12:56:33 UTC
(commons-statistics) 02/07: STATISTICS-90: Support statistic creation using an array range
This is an automated email from the ASF dual-hosted git repository.
aherbert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-statistics.git
commit b10193b0a152a7a744f5983440ac9f81e7158fcf
Author: Alex Herbert <ah...@apache.org>
AuthorDate: Tue Mar 18 17:03:15 2025 +0000
STATISTICS-90: Support statistic creation using an array range
Update for double statistics.
---
.../statistics/descriptive/DoubleStatistics.java | 141 +++++++++++++++++----
.../statistics/descriptive/FirstMoment.java | 60 ++++++---
.../statistics/descriptive/GeometricMean.java | 16 +++
.../commons/statistics/descriptive/Kurtosis.java | 17 +++
.../apache/commons/statistics/descriptive/Max.java | 33 +++++
.../commons/statistics/descriptive/Mean.java | 19 +++
.../apache/commons/statistics/descriptive/Min.java | 33 +++++
.../commons/statistics/descriptive/Product.java | 33 +++++
.../statistics/descriptive/RangeBiFunction.java | 41 ++++++
.../statistics/descriptive/RangeFunction.java | 39 ++++++
.../commons/statistics/descriptive/Skewness.java | 17 +++
.../statistics/descriptive/StandardDeviation.java | 19 +++
.../commons/statistics/descriptive/Statistics.java | 82 ++++++++++++
.../apache/commons/statistics/descriptive/Sum.java | 18 +++
.../descriptive/SumOfCubedDeviations.java | 45 +++++--
.../descriptive/SumOfFourthDeviations.java | 41 +++++-
.../commons/statistics/descriptive/SumOfLogs.java | 33 +++++
.../descriptive/SumOfSquaredDeviations.java | 43 +++++--
.../statistics/descriptive/SumOfSquares.java | 35 ++++-
.../commons/statistics/descriptive/Variance.java | 19 +++
.../descriptive/BaseDoubleStatisticTest.java | 79 ++++++++++++
.../descriptive/DoubleStatisticsTest.java | 89 +++++++++++++
.../statistics/descriptive/GeometricMeanTest.java | 5 +
.../statistics/descriptive/KurtosisTest.java | 5 +
.../commons/statistics/descriptive/MaxTest.java | 5 +
.../commons/statistics/descriptive/MeanTest.java | 5 +
.../commons/statistics/descriptive/MinTest.java | 5 +
.../statistics/descriptive/ProductTest.java | 5 +
.../statistics/descriptive/SkewnessTest.java | 5 +
.../descriptive/StandardDeviationTest.java | 5 +
.../statistics/descriptive/StatisticsTest.java | 30 +++++
.../descriptive/SumOfCubedDeviationsTest.java | 7 +
.../descriptive/SumOfFourthDeviationsTest.java | 17 ++-
.../statistics/descriptive/SumOfLogsTest.java | 5 +
.../statistics/descriptive/SumOfSquaresTest.java | 5 +
.../commons/statistics/descriptive/SumTest.java | 5 +
.../commons/statistics/descriptive/TestData.java | 23 ++++
.../statistics/descriptive/VarianceTest.java | 5 +
38 files changed, 1015 insertions(+), 74 deletions(-)
diff --git a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/DoubleStatistics.java b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/DoubleStatistics.java
index 5a4b329..5824123 100644
--- a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/DoubleStatistics.java
+++ b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/DoubleStatistics.java
@@ -18,7 +18,6 @@ package org.apache.commons.statistics.descriptive;
import java.util.Objects;
import java.util.Set;
-import java.util.function.BiFunction;
import java.util.function.DoubleConsumer;
import java.util.function.Function;
@@ -68,19 +67,19 @@ public final class DoubleStatistics implements DoubleConsumer {
private static final double[] NO_VALUES = {};
/** The {@link Min} constructor. */
- private Function<double[], Min> min;
+ private RangeFunction<double[], Min> min;
/** The {@link Max} constructor. */
- private Function<double[], Max> max;
+ private RangeFunction<double[], Max> max;
/** The moment constructor. May return any instance of {@link FirstMoment}. */
- private BiFunction<org.apache.commons.numbers.core.Sum, double[], FirstMoment> moment;
+ private RangeBiFunction<org.apache.commons.numbers.core.Sum, double[], FirstMoment> moment;
/** The {@link Sum} constructor. */
private Function<org.apache.commons.numbers.core.Sum, Sum> sum;
/** The {@link Product} constructor. */
- private Function<double[], Product> product;
+ private RangeFunction<double[], Product> product;
/** The {@link SumOfSquares} constructor. */
- private Function<double[], SumOfSquares> sumOfSquares;
+ private RangeFunction<double[], SumOfSquares> sumOfSquares;
/** The {@link SumOfLogs} constructor. */
- private Function<double[], SumOfLogs> sumOfLogs;
+ private RangeFunction<double[], SumOfLogs> sumOfLogs;
/** The order of the moment. It corresponds to the power computed by the {@link FirstMoment}
* instance constructed by {@link #moment}. This should only be increased from the default
* of zero (corresponding to no moment computation). */
@@ -105,22 +104,22 @@ public final class DoubleStatistics implements DoubleConsumer {
switch (statistic) {
case GEOMETRIC_MEAN:
case SUM_OF_LOGS:
- sumOfLogs = SumOfLogs::of;
+ sumOfLogs = SumOfLogs::createFromRange;
break;
case KURTOSIS:
createMoment(4);
break;
case MAX:
- max = Max::of;
+ max = Max::createFromRange;
break;
case MEAN:
createMoment(1);
break;
case MIN:
- min = Min::of;
+ min = Min::createFromRange;
break;
case PRODUCT:
- product = Product::of;
+ product = Product::createFromRange;
break;
case SKEWNESS:
createMoment(3);
@@ -133,7 +132,7 @@ public final class DoubleStatistics implements DoubleConsumer {
sum = Sum::new;
break;
case SUM_OF_SQUARES:
- sumOfSquares = SumOfSquares::of;
+ sumOfSquares = SumOfSquares::createFromRange;
break;
default:
throw new IllegalArgumentException(UNSUPPORTED_STATISTIC + statistic);
@@ -151,14 +150,14 @@ public final class DoubleStatistics implements DoubleConsumer {
if (order > momentOrder) {
momentOrder = order;
if (order == 4) {
- moment = SumOfFourthDeviations::create;
+ moment = SumOfFourthDeviations::createFromRange;
} else if (order == 3) {
- moment = SumOfCubedDeviations::create;
+ moment = SumOfCubedDeviations::createFromRange;
} else if (order == 2) {
- moment = SumOfSquaredDeviations::create;
+ moment = SumOfSquaredDeviations::createFromRange;
} else {
// Assume order == 1
- moment = FirstMoment::create;
+ moment = FirstMoment::createFromRange;
}
}
}
@@ -181,7 +180,7 @@ public final class DoubleStatistics implements DoubleConsumer {
* @return {@code DoubleStatistics} instance.
*/
public DoubleStatistics build() {
- return build(NO_VALUES);
+ return create(NO_VALUES, 0, 0);
}
/**
@@ -196,24 +195,59 @@ public final class DoubleStatistics implements DoubleConsumer {
*/
public DoubleStatistics build(double... values) {
Objects.requireNonNull(values, "values");
+ return create(values, 0, values.length);
+ }
+
+ /**
+ * Builds a {@code DoubleStatistics} instance using the specified range of {@code values}.
+ *
+ * <p>Note: {@code DoubleStatistics} computed using
+ * {@link DoubleStatistics#accept(double) accept} may be
+ * different from this instance.
+ *
+ * @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
+ * @return {@code DoubleStatistics} instance.
+ * @throws IndexOutOfBoundsException if the sub-range is out of bounds
+ */
+ public DoubleStatistics build(double[] values, int from, int to) {
+ Statistics.checkFromToIndex(from, to, values.length);
+ return create(values, from, to);
+ }
+
+ /**
+ * Builds a {@code DoubleStatistics} instance using the input {@code values}.
+ *
+ * <p>Note: {@code DoubleStatistics} computed using
+ * {@link DoubleStatistics#accept(double) accept} may be
+ * different from this instance.
+ *
+ * <p>Warning: No range checks are performed.
+ *
+ * @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
+ * @return {@code DoubleStatistics} instance.
+ */
+ private DoubleStatistics create(double[] values, int from, int to) {
// Create related statistics
FirstMoment m = null;
Sum sumStat = null;
if (moment != null || sum != null) {
- final org.apache.commons.numbers.core.Sum s =
- org.apache.commons.numbers.core.Sum.of(values);
- m = create(moment, s, values);
+ final org.apache.commons.numbers.core.Sum s = Statistics.sum(values, from, to);
+ m = create(moment, s, values, from, to);
sumStat = create(sum, s);
}
return new DoubleStatistics(
- values.length,
- create(min, values),
- create(max, values),
+ to - from,
+ create(min, values, from, to),
+ create(max, values, from, to),
m,
sumStat,
- create(product, values),
- create(sumOfSquares, values),
- create(sumOfLogs, values),
+ create(product, values, from, to),
+ create(sumOfSquares, values, from, to),
+ create(sumOfLogs, values, from, to),
config);
}
@@ -233,6 +267,24 @@ public final class DoubleStatistics implements DoubleConsumer {
return null;
}
+ /**
+ * Creates the object from the {@code values}.
+ *
+ * @param <S> value type
+ * @param <T> object type
+ * @param constructor Constructor.
+ * @param values Values
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
+ * @return the instance
+ */
+ private static <S, T> T create(RangeFunction<S, T> constructor, S values, int from, int to) {
+ if (constructor != null) {
+ return constructor.apply(values, from, to);
+ }
+ return null;
+ }
+
/**
* Creates the object from the values {@code r} and {@code s}.
*
@@ -242,11 +294,13 @@ public final class DoubleStatistics implements DoubleConsumer {
* @param constructor Constructor.
* @param r Value.
* @param s Value.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
* @return the instance
*/
- private static <R, S, T> T create(BiFunction<R, S, T> constructor, R r, S s) {
+ private static <R, S, T> T create(RangeBiFunction<R, S, T> constructor, R r, S s, int from, int to) {
if (constructor != null) {
- return constructor.apply(r, s);
+ return constructor.apply(r, s, from, to);
}
return null;
}
@@ -322,6 +376,37 @@ public final class DoubleStatistics implements DoubleConsumer {
return b.build(values);
}
+ /**
+ * Returns a new instance configured to compute the specified {@code statistics}
+ * populated using the specified range of {@code values}.
+ *
+ * <p>Use this method to create an instance populated with part of an array of
+ * {@code double[]} data, e.g. to use the first half of the data:
+ *
+ * <pre>
+ * double[] data = ...
+ * DoubleStatistics stats = DoubleStatistics.of(
+ * EnumSet.of(Statistic.MIN, Statistic.MAX),
+ * data, 0, data.length / 2);
+ * </pre>
+ *
+ * @param statistics Statistics to compute.
+ * @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
+ * @return the instance
+ * @throws IllegalArgumentException if there are no {@code statistics} to compute.
+ * @throws IndexOutOfBoundsException if the sub-range is out of bounds
+ */
+ public static DoubleStatistics ofRange(Set<Statistic> statistics, double[] values, int from, int to) {
+ if (statistics.isEmpty()) {
+ throw new IllegalArgumentException(NO_CONFIGURED_STATISTICS);
+ }
+ final Builder b = new Builder();
+ statistics.forEach(b::add);
+ return b.build(values, from, to);
+ }
+
/**
* Returns a new builder configured to create instances to compute the specified
* {@code statistics}.
diff --git a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/FirstMoment.java b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/FirstMoment.java
index 1303b92..9531b13 100644
--- a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/FirstMoment.java
+++ b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/FirstMoment.java
@@ -153,7 +153,28 @@ class FirstMoment implements DoubleConsumer {
}
// In the typical use-case a sum of values will not overflow and
// is faster than the rolling algorithm
- return create(org.apache.commons.numbers.core.Sum.of(values), values);
+ return createFromRange(org.apache.commons.numbers.core.Sum.of(values), values, 0, values.length);
+ }
+
+ /**
+ * Returns an instance populated using the specified range of {@code values}.
+ *
+ * <p>Note: {@code FirstMoment} computed using {@link #accept} may be different from
+ * this instance.
+ *
+ * <p>Warning: No range checks are performed.
+ *
+ * @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
+ * @return {@code FirstMoment} instance.
+ * @throws IndexOutOfBoundsException if the sub-range is out of bounds
+ */
+ static FirstMoment ofRange(double[] values, int from, int to) {
+ if (from == to) {
+ return new FirstMoment();
+ }
+ return createFromRange(Statistics.sum(values, from, to), values, from, to);
}
/**
@@ -165,38 +186,43 @@ class FirstMoment implements DoubleConsumer {
* <p>This method is used by {@link DoubleStatistics} using a sum that can be reused
* for the {@link Sum} statistic.
*
+ * <p>Warning: No range checks are performed.
+ *
* @param sum Sum of the values.
* @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
* @return {@code FirstMoment} instance.
*/
- static FirstMoment create(org.apache.commons.numbers.core.Sum sum, double[] values) {
+ static FirstMoment createFromRange(org.apache.commons.numbers.core.Sum sum,
+ double[] values, int from, int to) {
// Protect against empty values
- if (values.length == 0) {
+ if (from == to) {
return new FirstMoment();
}
final double s = sum.getAsDouble();
if (Double.isFinite(s)) {
- return new FirstMoment(s / values.length, values.length);
+ return new FirstMoment(s / (to - from), to - from);
}
// "Corrected two-pass algorithm"
// First pass
- final FirstMoment m1 = create(values);
+ final FirstMoment m1 = create(values, from, to);
final double xbar = m1.getFirstMoment();
if (!Double.isFinite(xbar)) {
return m1;
}
// Second pass
double correction = 0;
- for (final double x : values) {
- correction += x - xbar;
+ for (int i = from; i < to; i++) {
+ correction += values[i] - xbar;
}
// Note: Correction may be infinite
if (Double.isFinite(correction)) {
// Down scale the correction to the half representation
- m1.m1 += DOWNSCALE * correction / values.length;
+ m1.m1 += DOWNSCALE * correction / m1.n;
}
return m1;
}
@@ -212,14 +238,16 @@ class FirstMoment implements DoubleConsumer {
* </ul>
*
* @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
* @return the first moment
*/
- private static FirstMoment create(double[] values) {
+ private static FirstMoment create(double[] values, int from, int to) {
double m1 = 0;
int n = 0;
- for (final double x : values) {
+ for (int i = from; i < to; i++) {
// Downscale to avoid overflow for all finite input
- m1 += (x * DOWNSCALE - m1) / ++n;
+ m1 += (values[i] * DOWNSCALE - m1) / ++n;
}
final FirstMoment m = new FirstMoment();
m.n = n;
@@ -227,7 +255,7 @@ class FirstMoment implements DoubleConsumer {
m.m1 = m1;
// The non-finite value is only relevant if the data contains inf/nan
if (!Double.isFinite(m1 * RESCALE)) {
- m.nonFiniteValue = computeNonFiniteValue(values);
+ m.nonFiniteValue = computeNonFiniteValue(values, from, to);
}
return m;
}
@@ -236,13 +264,15 @@ class FirstMoment implements DoubleConsumer {
* Compute the result in the event of non-finite values.
*
* @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
* @return the non-finite result
*/
- private static double computeNonFiniteValue(double[] values) {
+ private static double computeNonFiniteValue(double[] values, int from, int to) {
double sum = 0;
- for (final double x : values) {
+ for (int i = from; i < to; i++) {
// Scaling down values prevents overflow of finites.
- sum += x * Double.MIN_NORMAL;
+ sum += values[i] * Double.MIN_NORMAL;
}
return sum;
}
diff --git a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/GeometricMean.java b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/GeometricMean.java
index c107ecb..a01f597 100644
--- a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/GeometricMean.java
+++ b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/GeometricMean.java
@@ -111,6 +111,22 @@ public final class GeometricMean implements DoubleStatistic, StatisticAccumulato
return new GeometricMean(SumOfLogs.of(values), values.length);
}
+ /**
+ * Returns an instance populated using the specified range of {@code values}.
+ *
+ * <p>When the range is empty, the result is {@code NaN}.
+ *
+ * @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
+ * @return {@code GeometricMean} instance.
+ * @throws IndexOutOfBoundsException if the sub-range is out of bounds
+ */
+ public static GeometricMean ofRange(double[] values, int from, int to) {
+ // Range checks performed by the sum-of-logs
+ return new GeometricMean(SumOfLogs.ofRange(values, from, to), to - from);
+ }
+
/**
* Returns an instance populated using the input {@code values}.
*
diff --git a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Kurtosis.java b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Kurtosis.java
index 909402d..c26c9b7 100644
--- a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Kurtosis.java
+++ b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Kurtosis.java
@@ -148,6 +148,23 @@ public final class Kurtosis implements DoubleStatistic, StatisticAccumulator<Kur
return new Kurtosis(SumOfFourthDeviations.of(values));
}
+ /**
+ * Returns an instance populated using the specified range of {@code values}.
+ *
+ * <p>Note: {@code Kurtosis} computed using {@link #accept(double) accept} may be
+ * different from this instance.
+ *
+ * @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
+ * @return {@code Kurtosis} instance.
+ * @throws IndexOutOfBoundsException if the sub-range is out of bounds
+ */
+ public static Kurtosis ofRange(double[] values, int from, int to) {
+ Statistics.checkFromToIndex(from, to, values.length);
+ return new Kurtosis(SumOfFourthDeviations.ofRange(values, from, to));
+ }
+
/**
* Returns an instance populated using the input {@code values}.
*
diff --git a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Max.java b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Max.java
index 5ac6ad8..50d9ab5 100644
--- a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Max.java
+++ b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Max.java
@@ -83,6 +83,39 @@ public final class Max implements DoubleStatistic, StatisticAccumulator<Max> {
return Statistics.add(new Max(), values);
}
+ /**
+ * Returns an instance populated using the specified range of {@code values}.
+ *
+ * <p>The result is {@code NaN} if any of the values is {@code NaN}.
+ *
+ * <p>When the range is empty, the result is
+ * {@link Double#NEGATIVE_INFINITY negative infinity}.
+ *
+ * @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
+ * @return {@code Max} instance.
+ * @throws IndexOutOfBoundsException if the sub-range is out of bounds
+ */
+ public static Max ofRange(double[] values, int from, int to) {
+ Statistics.checkFromToIndex(from, to, values.length);
+ return createFromRange(values, from, to);
+ }
+
+ /**
+ * Create an instance using the specified range of {@code values}.
+ *
+ * <p>Warning: No range checks are performed.
+ *
+ * @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
+ * @return {@code Max} instance.
+ */
+ static Max createFromRange(double[] values, int from, int to) {
+ return Statistics.add(new Max(), values, from, to);
+ }
+
/**
* Updates the state of the statistic to reflect the addition of {@code value}.
*
diff --git a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Mean.java b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Mean.java
index 0eb3a8c..7d2639e 100644
--- a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Mean.java
+++ b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Mean.java
@@ -124,6 +124,25 @@ public final class Mean implements DoubleStatistic, StatisticAccumulator<Mean> {
return new Mean(FirstMoment.of(values));
}
+ /**
+ * Returns an instance populated using the specified range of {@code values}.
+ *
+ * <p>Note: {@code Mean} computed using {@link #accept(double) accept} may be
+ * different from this mean.
+ *
+ * <p>See {@link Mean} for details on the computing algorithm.
+ *
+ * @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
+ * @return {@code Mean} instance.
+ * @throws IndexOutOfBoundsException if the sub-range is out of bounds
+ */
+ public static Mean ofRange(double[] values, int from, int to) {
+ Statistics.checkFromToIndex(from, to, values.length);
+ return new Mean(FirstMoment.ofRange(values, from, to));
+ }
+
/**
* Updates the state of the statistic to reflect the addition of {@code value}.
*
diff --git a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Min.java b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Min.java
index 7601f6b..aac2ced 100644
--- a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Min.java
+++ b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Min.java
@@ -83,6 +83,39 @@ public final class Min implements DoubleStatistic, StatisticAccumulator<Min> {
return Statistics.add(new Min(), values);
}
+ /**
+ * Returns an instance populated using the specified range of {@code values}.
+ *
+ * <p>The result is {@code NaN} if any of the values is {@code NaN}.
+ *
+ * <p>When the range is empty, the result is
+ * {@link Double#POSITIVE_INFINITY positive infinity}.
+ *
+ * @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
+ * @return {@code Min} instance.
+ * @throws IndexOutOfBoundsException if the sub-range is out of bounds
+ */
+ public static Min ofRange(double[] values, int from, int to) {
+ Statistics.checkFromToIndex(from, to, values.length);
+ return createFromRange(values, from, to);
+ }
+
+ /**
+ * Create an instance using the specified range of {@code values}.
+ *
+ * <p>Warning: No range checks are performed.
+ *
+ * @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
+ * @return {@code Min} instance.
+ */
+ static Min createFromRange(double[] values, int from, int to) {
+ return Statistics.add(new Min(), values, from, to);
+ }
+
/**
* Updates the state of the statistic to reflect the addition of {@code value}.
*
diff --git a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Product.java b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Product.java
index d172bdc..09a6204 100644
--- a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Product.java
+++ b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Product.java
@@ -80,6 +80,39 @@ public final class Product implements DoubleStatistic, StatisticAccumulator<Prod
return Statistics.add(new Product(), values);
}
+ /**
+ * Returns an instance populated using the specified range of {@code values}.
+ *
+ * <p>The result is {@code NaN} if any of the values is {@code NaN}
+ * or the product at any point is a {@code NaN}.
+ *
+ * <p>When the range is empty, the result is one.
+ *
+ * @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
+ * @return {@code Product} instance.
+ * @throws IndexOutOfBoundsException if the sub-range is out of bounds
+ */
+ public static Product ofRange(double[] values, int from, int to) {
+ Statistics.checkFromToIndex(from, to, values.length);
+ return createFromRange(values, from, to);
+ }
+
+ /**
+ * Create an instance using the specified range of {@code values}.
+ *
+ * <p>Warning: No range checks are performed.
+ *
+ * @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
+ * @return {@code Product} instance.
+ */
+ static Product createFromRange(double[] values, int from, int to) {
+ return Statistics.add(new Product(), values, from, to);
+ }
+
/**
* Returns an instance populated using the input {@code values}.
*
diff --git a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/RangeBiFunction.java b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/RangeBiFunction.java
new file mode 100644
index 0000000..fdbf462
--- /dev/null
+++ b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/RangeBiFunction.java
@@ -0,0 +1,41 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.statistics.descriptive;
+
+/**
+ * Represents a function that accepts two objects and a range and produces a result.
+ *
+ * <p>This interface is similar to {@link java.util.function.BiFunction} with the addition
+ * of a range {@code [from, to)} argument to the functional method.
+ *
+ * @param <T> the type of the first argument to the function
+ * @param <U> the type of the second argument to the function
+ * @param <R> the type of the result of the function
+ */
+@FunctionalInterface
+interface RangeBiFunction<T, U, R> {
+ /**
+ * Applies this function to the given arguments.
+ *
+ * @param t the function argument
+ * @param u the second function argument
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
+ * @return the function result
+ */
+ R apply(T t, U u, int from, int to);
+}
diff --git a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/RangeFunction.java b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/RangeFunction.java
new file mode 100644
index 0000000..521e8f8
--- /dev/null
+++ b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/RangeFunction.java
@@ -0,0 +1,39 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.statistics.descriptive;
+
+/**
+ * Represents a function that accepts an object and a range and produces a result.
+ *
+ * <p>This interface is similar to {@link java.util.function.Function} with the addition
+ * of a range {@code [from, to)} argument to the functional method.
+ *
+ * @param <T> the type of the input to the function
+ * @param <R> the type of the result of the function
+ */
+@FunctionalInterface
+interface RangeFunction<T, R> {
+ /**
+ * Applies this function to the given arguments.
+ *
+ * @param t the function argument
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
+ * @return the function result
+ */
+ R apply(T t, int from, int to);
+}
diff --git a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Skewness.java b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Skewness.java
index b70d967..8a3df8a 100644
--- a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Skewness.java
+++ b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Skewness.java
@@ -150,6 +150,23 @@ public final class Skewness implements DoubleStatistic, StatisticAccumulator<Ske
return new Skewness(SumOfCubedDeviations.of(values));
}
+ /**
+ * Returns an instance populated using the specified range of {@code values}.
+ *
+ * <p>Note: {@code Skewness} computed using {@link #accept(double) accept} may be
+ * different from this instance.
+ *
+ * @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
+ * @return {@code Skewness} instance.
+ * @throws IndexOutOfBoundsException if the sub-range is out of bounds
+ */
+ public static Skewness ofRange(double[] values, int from, int to) {
+ Statistics.checkFromToIndex(from, to, values.length);
+ return new Skewness(SumOfCubedDeviations.ofRange(values, from, to));
+ }
+
/**
* Returns an instance populated using the input {@code values}.
*
diff --git a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/StandardDeviation.java b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/StandardDeviation.java
index 4629487..6a46e05 100644
--- a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/StandardDeviation.java
+++ b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/StandardDeviation.java
@@ -141,6 +141,25 @@ public final class StandardDeviation implements DoubleStatistic, StatisticAccumu
return new StandardDeviation(SumOfSquaredDeviations.of(values));
}
+ /**
+ * Returns an instance populated using the specified range of {@code values}.
+ *
+ * <p>Note: {@code StandardDeviation} computed using {@link #accept(double) accept} may be
+ * different from this standard deviation.
+ *
+ * <p>See {@link StandardDeviation} for details on the computing algorithm.
+ *
+ * @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
+ * @return {@code StandardDeviation} instance.
+ * @throws IndexOutOfBoundsException if the sub-range is out of bounds
+ */
+ public static StandardDeviation ofRange(double[] values, int from, int to) {
+ Statistics.checkFromToIndex(from, to, values.length);
+ return new StandardDeviation(SumOfSquaredDeviations.ofRange(values, from, to));
+ }
+
/**
* Updates the state of the statistic to reflect the addition of {@code value}.
*
diff --git a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Statistics.java b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Statistics.java
index 90bf452..71bc74c 100644
--- a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Statistics.java
+++ b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Statistics.java
@@ -89,6 +89,24 @@ final class Statistics {
return statistic;
}
+ /**
+ * Add the specified range of {@code values} to the {@code statistic}.
+ * <p>Warning: No range checks are performed.
+ *
+ * @param <T> Type of the statistic
+ * @param statistic Statistic.
+ * @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
+ * @return the statistic
+ */
+ static <T extends DoubleConsumer> T add(T statistic, double[] values, int from, int to) {
+ for (int i = from; i < to; i++) {
+ statistic.accept(values[i]);
+ }
+ return statistic;
+ }
+
/**
* Add all the {@code values} to the {@code statistic}.
*
@@ -343,4 +361,68 @@ final class Statistics {
a.combine(b);
}
}
+
+ /**
+ * Checks if the sub-range from fromIndex (inclusive) to toIndex (exclusive) is
+ * within the bounds of range from 0 (inclusive) to length (exclusive).
+ *
+ * <p>This function provides the functionality of
+ * {@code java.utils.Objects.checkFromToIndex} introduced in JDK 9. The <a
+ * href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Objects.html#checkFromToIndex(int,int,int)">Objects</a>
+ * javadoc has been reproduced for reference. The return value has been changed
+ * to void.
+ *
+ * <p>The sub-range is defined to be out of bounds if any of the following
+ * inequalities is true:
+ * <ul>
+ * <li>{@code fromIndex < 0}
+ * <li>{@code fromIndex > toIndex}
+ * <li>{@code toIndex > length}
+ * <li>{@code length < 0}, which is implied from the former inequalities
+ * </ul>
+ *
+ * @param fromIndex Lower-bound (inclusive) of the sub-range.
+ * @param toIndex Upper-bound (exclusive) of the sub-range.
+ * @param length Upper-bound (exclusive) of the range.
+ * @throws IndexOutOfBoundsException if the sub-range is out of bounds
+ */
+ static void checkFromToIndex(int fromIndex, int toIndex, int length) {
+ // Checks as documented above
+ if (fromIndex < 0 || fromIndex > toIndex || toIndex > length) {
+ throw new IndexOutOfBoundsException(
+ msgRangeOutOfBounds(fromIndex, toIndex, length));
+ }
+ }
+
+ // Message formatting moved to separate methods to assist inlining of the validation methods.
+
+ /**
+ * Format a message when range [from, to) is not entirely within the length.
+ *
+ * @param fromIndex Lower-bound (inclusive) of the sub-range.
+ * @param toIndex Upper-bound (exclusive) of the sub-range.
+ * @param length Upper-bound (exclusive) of the range.
+ * @return the message
+ */
+ private static String msgRangeOutOfBounds(int fromIndex, int toIndex, int length) {
+ return String.format("Range [%d, %d) out of bounds for length %d", fromIndex, toIndex, length);
+ }
+
+ /**
+ * Sum the specified range of {@code values}.
+ *
+ * <p>Warning: No range checks are performed.
+ *
+ * @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
+ * @return the sum
+ */
+ static org.apache.commons.numbers.core.Sum sum(double[] values, int from, int to) {
+ final org.apache.commons.numbers.core.Sum s = org.apache.commons.numbers.core.Sum.create();
+ for (int i = from; i < to; i++) {
+ s.accept(values[i]);
+ }
+ return s;
+ }
}
diff --git a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Sum.java b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Sum.java
index 9c666fe..4e11054 100644
--- a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Sum.java
+++ b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Sum.java
@@ -96,6 +96,24 @@ public final class Sum implements DoubleStatistic, StatisticAccumulator<Sum> {
return new Sum(org.apache.commons.numbers.core.Sum.of(values));
}
+ /**
+ * Returns an instance populated using the specified range of {@code values}.
+ *
+ * <p>The result is {@code NaN} if any of the values is {@code NaN}
+ * or the sum at any point is a {@code NaN}.
+ *
+ * <p>When the range is empty, the result is zero.
+ *
+ * @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
+ * @return {@code Sum} instance.
+ */
+ public static Sum ofRange(double[] values, int from, int to) {
+ Statistics.checkFromToIndex(from, to, values.length);
+ return new Sum(Statistics.sum(values, from, to));
+ }
+
/**
* Updates the state of the statistic to reflect the addition of {@code value}.
*
diff --git a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/SumOfCubedDeviations.java b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/SumOfCubedDeviations.java
index df96614..5d7e74e 100644
--- a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/SumOfCubedDeviations.java
+++ b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/SumOfCubedDeviations.java
@@ -130,7 +130,27 @@ class SumOfCubedDeviations extends SumOfSquaredDeviations {
if (values.length == 0) {
return new SumOfCubedDeviations();
}
- return create(SumOfSquaredDeviations.of(values), values);
+ return create(SumOfSquaredDeviations.of(values), values, 0, values.length);
+ }
+
+ /**
+ * Returns an instance populated using the specified range of {@code values}.
+ *
+ * <p>Note: {@code SumOfCubedDeviations} computed using {@link #accept(double) accept} may be
+ * different from this instance.
+ *
+ * <p>Warning: No range checks are performed.
+ *
+ * @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
+ * @return {@code SumOfCubedDeviations} instance.
+ */
+ static SumOfCubedDeviations ofRange(double[] values, int from, int to) {
+ if (from == to) {
+ return new SumOfCubedDeviations();
+ }
+ return create(SumOfSquaredDeviations.ofRange(values, from, to), values, from, to);
}
/**
@@ -140,15 +160,20 @@ class SumOfCubedDeviations extends SumOfSquaredDeviations {
* This method is used by {@link DoubleStatistics} using a sum that can be reused
* for the {@link Sum} statistic.
*
+ * <p>Warning: No range checks are performed.
+ *
* @param sum Sum of the values.
* @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
* @return {@code SumOfCubedDeviations} instance.
*/
- static SumOfCubedDeviations create(org.apache.commons.numbers.core.Sum sum, double[] values) {
- if (values.length == 0) {
+ static SumOfCubedDeviations createFromRange(org.apache.commons.numbers.core.Sum sum,
+ double[] values, int from, int to) {
+ if (from == to) {
return new SumOfCubedDeviations();
}
- return create(SumOfSquaredDeviations.create(sum, values), values);
+ return create(SumOfSquaredDeviations.createFromRange(sum, values, from, to), values, from, to);
}
/**
@@ -156,9 +181,11 @@ class SumOfCubedDeviations extends SumOfSquaredDeviations {
*
* @param ss Sum of squared deviations.
* @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
* @return {@code SumOfCubedDeviations} instance.
*/
- private static SumOfCubedDeviations create(SumOfSquaredDeviations ss, double[] values) {
+ private static SumOfCubedDeviations create(SumOfSquaredDeviations ss, double[] values, int from, int to) {
// Edge cases
final double xbar = ss.getFirstMoment();
if (!Double.isFinite(xbar)) {
@@ -170,16 +197,16 @@ class SumOfCubedDeviations extends SumOfSquaredDeviations {
// +/- values around a mean of zero, or approximately sqrt(MAX_VALUE / 2^31) = 2.89e149.
// In this case the sum cubed could be finite due to cancellation
// but this cannot be computed. Only a small array can be known to be zero.
- return new SumOfCubedDeviations(values.length <= LENGTH_TWO ? 0 : Double.NaN, ss);
+ return new SumOfCubedDeviations(ss.n <= LENGTH_TWO ? 0 : Double.NaN, ss);
}
// Compute the sum of cubed deviations.
double s = 0;
// n=1: no deviation
// n=2: the two deviations from the mean are equal magnitude
// and opposite sign. So the sum-of-cubed deviations is zero.
- if (values.length > LENGTH_TWO) {
- for (final double x : values) {
- s += pow3(x - xbar);
+ if (ss.n > LENGTH_TWO) {
+ for (int i = from; i < to; i++) {
+ s += pow3(values[i] - xbar);
}
}
return new SumOfCubedDeviations(s, ss);
diff --git a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/SumOfFourthDeviations.java b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/SumOfFourthDeviations.java
index 918a843..1e78a59 100644
--- a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/SumOfFourthDeviations.java
+++ b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/SumOfFourthDeviations.java
@@ -122,7 +122,27 @@ class SumOfFourthDeviations extends SumOfCubedDeviations {
if (values.length == 0) {
return new SumOfFourthDeviations();
}
- return create(SumOfCubedDeviations.of(values), values);
+ return create(SumOfCubedDeviations.of(values), values, 0, values.length);
+ }
+
+ /**
+ * Returns an instance populated using the specified range of {@code values}.
+ *
+ * <p>Note: {@code SumOfFourthDeviations} computed using {@link #accept accept} may be
+ * different from this instance.
+ *
+ * <p>Warning: No range checks are performed.
+ *
+ * @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
+ * @return {@code SumOfFourthDeviations} instance.
+ */
+ static SumOfFourthDeviations ofRange(double[] values, int from, int to) {
+ if (from == to) {
+ return new SumOfFourthDeviations();
+ }
+ return create(SumOfCubedDeviations.ofRange(values, from, to), values, from, to);
}
/**
@@ -132,15 +152,20 @@ class SumOfFourthDeviations extends SumOfCubedDeviations {
* This method is used by {@link DoubleStatistics} using a sum that can be reused
* for the {@link Sum} statistic.
*
+ * <p>Warning: No range checks are performed.
+ *
* @param sum Sum of the values.
* @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
* @return {@code SumOfFourthDeviations} instance.
*/
- static SumOfFourthDeviations create(org.apache.commons.numbers.core.Sum sum, double[] values) {
- if (values.length == 0) {
+ static SumOfFourthDeviations createFromRange(org.apache.commons.numbers.core.Sum sum,
+ double[] values, int from, int to) {
+ if (from == to) {
return new SumOfFourthDeviations();
}
- return create(SumOfCubedDeviations.create(sum, values), values);
+ return create(SumOfCubedDeviations.createFromRange(sum, values, from, to), values, from, to);
}
/**
@@ -148,9 +173,11 @@ class SumOfFourthDeviations extends SumOfCubedDeviations {
*
* @param sc Sum of cubed deviations.
* @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
* @return {@code SumOfFourthDeviations} instance.
*/
- private static SumOfFourthDeviations create(SumOfCubedDeviations sc, double[] values) {
+ private static SumOfFourthDeviations create(SumOfCubedDeviations sc, double[] values, int from, int to) {
// Edge cases
final double xbar = sc.getFirstMoment();
if (!Double.isFinite(xbar) ||
@@ -162,8 +189,8 @@ class SumOfFourthDeviations extends SumOfCubedDeviations {
// Compute the sum of fourth (quad) deviations.
// Note: This handles n=1.
double s = 0;
- for (final double x : values) {
- s += pow4(x - xbar);
+ for (int i = from; i < to; i++) {
+ s += pow4(values[i] - xbar);
}
return new SumOfFourthDeviations(s, sc);
}
diff --git a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/SumOfLogs.java b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/SumOfLogs.java
index 2de25c5..bab1848 100644
--- a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/SumOfLogs.java
+++ b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/SumOfLogs.java
@@ -95,6 +95,39 @@ public final class SumOfLogs implements DoubleStatistic, StatisticAccumulator<Su
return Statistics.add(new SumOfLogs(), values);
}
+ /**
+ * Returns an instance populated using the specified range of {@code values}.
+ *
+ * <p>The result is {@code NaN} if any of the values is {@code NaN}
+ * or negative; or the sum at any point is a {@code NaN}.
+ *
+ * <p>When the range is empty, the result is zero.
+ *
+ * @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
+ * @return {@code SumOfLogs} instance.
+ * @throws IndexOutOfBoundsException if the sub-range is out of bounds
+ */
+ public static SumOfLogs ofRange(double[] values, int from, int to) {
+ Statistics.checkFromToIndex(from, to, values.length);
+ return createFromRange(values, from, to);
+ }
+
+ /**
+ * Create an instance using the specified range of {@code values}.
+ *
+ * <p>Warning: No range checks are performed.
+ *
+ * @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
+ * @return {@code SumOfLogs} instance.
+ */
+ static SumOfLogs createFromRange(double[] values, int from, int to) {
+ return Statistics.add(new SumOfLogs(), values, from, to);
+ }
+
/**
* Returns an instance populated using the input {@code values}.
*
diff --git a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/SumOfSquaredDeviations.java b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/SumOfSquaredDeviations.java
index d890120..37af330 100644
--- a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/SumOfSquaredDeviations.java
+++ b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/SumOfSquaredDeviations.java
@@ -115,7 +115,27 @@ class SumOfSquaredDeviations extends FirstMoment {
if (values.length == 0) {
return new SumOfSquaredDeviations();
}
- return create(FirstMoment.of(values), values);
+ return create(FirstMoment.of(values), values, 0, values.length);
+ }
+
+ /**
+ * Returns an instance populated using the specified range of {@code values}.
+ *
+ * <p>Note: {@code SumOfSquaredDeviations} computed using {@link #accept accept} may be
+ * different from this instance.
+ *
+ * <p>Warning: No range checks are performed.
+ *
+ * @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
+ * @return {@code SumOfSquaredDeviations} instance.
+ */
+ static SumOfSquaredDeviations ofRange(double[] values, int from, int to) {
+ if (from == to) {
+ return new SumOfSquaredDeviations();
+ }
+ return create(FirstMoment.ofRange(values, from, to), values, from, to);
}
/**
@@ -125,15 +145,20 @@ class SumOfSquaredDeviations extends FirstMoment {
* This method is used by {@link DoubleStatistics} using a sum that can be reused
* for the {@link Sum} statistic.
*
+ * <p>Warning: No range checks are performed.
+ *
* @param sum Sum of the values.
* @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
* @return {@code SumOfSquaredDeviations} instance.
*/
- static SumOfSquaredDeviations create(org.apache.commons.numbers.core.Sum sum, double[] values) {
- if (values.length == 0) {
+ static SumOfSquaredDeviations createFromRange(org.apache.commons.numbers.core.Sum sum,
+ double[] values, int from, int to) {
+ if (from == to) {
return new SumOfSquaredDeviations();
}
- return create(FirstMoment.create(sum, values), values);
+ return create(FirstMoment.createFromRange(sum, values, from, to), values, from, to);
}
/**
@@ -141,9 +166,11 @@ class SumOfSquaredDeviations extends FirstMoment {
*
* @param m1 First moment.
* @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
* @return {@code SumOfSquaredDeviations} instance.
*/
- private static SumOfSquaredDeviations create(FirstMoment m1, double[] values) {
+ private static SumOfSquaredDeviations create(FirstMoment m1, double[] values, int from, int to) {
// "Corrected two-pass algorithm"
// See: Chan et al (1983) Equation 1.7
@@ -153,8 +180,8 @@ class SumOfSquaredDeviations extends FirstMoment {
}
double s = 0;
double ss = 0;
- for (final double x : values) {
- final double dx = x - xbar;
+ for (int i = from; i < to; i++) {
+ final double dx = values[i] - xbar;
s += dx;
ss += dx * dx;
}
@@ -165,7 +192,7 @@ class SumOfSquaredDeviations extends FirstMoment {
// when ss is infinite, assign it an infinite value which is its intended value.
final double sumSquaredDev = ss == Double.POSITIVE_INFINITY ?
Double.POSITIVE_INFINITY :
- ss - (s * s / values.length);
+ ss - (s * s / (to - from));
return new SumOfSquaredDeviations(sumSquaredDev, m1);
}
diff --git a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/SumOfSquares.java b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/SumOfSquares.java
index 9be57d0..829b700 100644
--- a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/SumOfSquares.java
+++ b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/SumOfSquares.java
@@ -74,8 +74,7 @@ public final class SumOfSquares implements DoubleStatistic, StatisticAccumulator
/**
* Returns an instance populated using the input {@code values}.
*
- * <p>The result is {@code NaN} if any of the values is {@code NaN}
- * or the product at any point is a {@code NaN}.
+ * <p>The result is {@code NaN} if any of the values is {@code NaN}.
*
* <p>When the input is an empty array, the result is zero.
*
@@ -86,6 +85,38 @@ public final class SumOfSquares implements DoubleStatistic, StatisticAccumulator
return Statistics.add(new SumOfSquares(), values);
}
+ /**
+ * Returns an instance populated using the specified range of {@code values}.
+ *
+ * <p>The result is {@code NaN} if any of the values is {@code NaN}.
+ *
+ * <p>When the range is empty, the result is zero.
+ *
+ * @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
+ * @return {@code SumOfSquares} instance.
+ * @throws IndexOutOfBoundsException if the sub-range is out of bounds
+ */
+ public static SumOfSquares ofRange(double[] values, int from, int to) {
+ Statistics.checkFromToIndex(from, to, values.length);
+ return createFromRange(values, from, to);
+ }
+
+ /**
+ * Create an instance using the specified range of {@code values}.
+ *
+ * <p>Warning: No range checks are performed.
+ *
+ * @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
+ * @return {@code SumOfSquares} instance.
+ */
+ static SumOfSquares createFromRange(double[] values, int from, int to) {
+ return Statistics.add(new SumOfSquares(), values, from, to);
+ }
+
/**
* Updates the state of the statistic to reflect the addition of {@code value}.
*
diff --git a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Variance.java b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Variance.java
index 75be1c9..7ceba94 100644
--- a/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Variance.java
+++ b/commons-statistics-descriptive/src/main/java/org/apache/commons/statistics/descriptive/Variance.java
@@ -137,6 +137,25 @@ public final class Variance implements DoubleStatistic, StatisticAccumulator<Var
return new Variance(SumOfSquaredDeviations.of(values));
}
+ /**
+ * Returns an instance populated using the specified range of {@code values}.
+ *
+ * <p>Note: {@code Variance} computed using {@link #accept(double) accept} may be
+ * different from this variance.
+ *
+ * <p>See {@link Variance} for details on the computing algorithm.
+ *
+ * @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
+ * @return {@code Variance} instance.
+ * @throws IndexOutOfBoundsException if the sub-range is out of bounds
+ */
+ public static Variance ofRange(double[] values, int from, int to) {
+ Statistics.checkFromToIndex(from, to, values.length);
+ return new Variance(SumOfSquaredDeviations.ofRange(values, from, to));
+ }
+
/**
* Updates the state of the statistic to reflect the addition of {@code value}.
*
diff --git a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/BaseDoubleStatisticTest.java b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/BaseDoubleStatisticTest.java
index 34431f5..ad99f2a 100644
--- a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/BaseDoubleStatisticTest.java
+++ b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/BaseDoubleStatisticTest.java
@@ -400,6 +400,16 @@ abstract class BaseDoubleStatisticTest<S extends DoubleStatistic & StatisticAccu
*/
protected abstract S create(double... values);
+ /**
+ * Creates the statistic from the {@code values} using the range {@code [from, to)}.
+ *
+ * @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
+ * @return the statistic
+ */
+ protected abstract S create(double[] values, int from, int to);
+
/**
* Get the maximum number of values that can be added where the statistic is
* considered empty.
@@ -803,6 +813,22 @@ abstract class BaseDoubleStatisticTest<S extends DoubleStatistic & StatisticAccu
return streamSingleArrayData(getToleranceArray(), StatisticTestData::getTolArray);
}
+ /**
+ * Stream the arguments to test the computation of the statistic using the
+ * {@link #create(double[], int, int)} method. The expected value is the same as
+ * using the {@link #create(double...)} method with the values from
+ * {@link Arrays#copyOfRange(double[], int, int)}.
+ *
+ * @return the stream
+ */
+ final Stream<double[]> testArrayRange() {
+ final Builder<double[]> b = Stream.builder();
+ data.forEach(d -> b.accept(d.getValues()));
+ dataNonFinite.forEach(d -> b.accept(d.getValues()));
+ dataCustom.forEach(d -> b.accept(d.getValues()));
+ return b.build();
+ }
+
/**
* Stream the arguments to test the computation of the statistic using a single
* {@code double[]} array.
@@ -969,6 +995,14 @@ abstract class BaseDoubleStatisticTest<S extends DoubleStatistic & StatisticAccu
assertEmpty(create(EMPTY), getToleranceArray());
}
+ /**
+ * Test the uninitialized state of the statistic created from an empty range of an array.
+ */
+ @Test
+ final void testEmptyArrayRange() {
+ assertEmpty(create(new double[10], 2, 2), getToleranceArray());
+ }
+
/**
* Assert the uninitialized state of the statistic.
*
@@ -1013,6 +1047,37 @@ abstract class BaseDoubleStatisticTest<S extends DoubleStatistic & StatisticAccu
assertStatistic(this::create, values, expected, tol);
}
+ /**
+ * Test the computation of the statistic using the {@link #create(double[], int, int)} method.
+ */
+ @ParameterizedTest
+ @MethodSource
+ final void testArrayRange(double[] values) {
+ // Test full range and half-range
+ assertStatistic(values, 0, values.length);
+ assertStatistic(values, 0, values.length >> 1);
+ assertStatistic(values, values.length >> 1, values.length);
+ // Random range
+ final long[] seed = TestHelper.createRNGSeed();
+ final UniformRandomProvider rng = TestHelper.createRNG(seed);
+ for (int repeat = RANDOM_PERMUTATIONS; --repeat >= 0;) {
+ final int i = rng.nextInt(values.length);
+ final int j = rng.nextInt(values.length);
+ assertStatistic(values, Math.min(i, j), Math.max(i, j));
+ }
+ }
+
+ /**
+ * Test the {@link #create(double[], int, int)} method throws with an invalid range.
+ */
+ @ParameterizedTest
+ @MethodSource(value = {"org.apache.commons.statistics.descriptive.TestData#arrayRangeTestData"})
+ final void testArrayRangeThrows(int from, int to, int length) {
+ final double[] values = new double[length];
+ Assertions.assertThrows(IndexOutOfBoundsException.class, () -> create(values, from, to),
+ () -> String.format("%s for range [%d, %d) in length %d", statisticName, from, to, length));
+ }
+
/**
* Test the computation of the statistic using the
* {@link java.util.function.DoubleConsumer#accept(double) accept} method for each
@@ -1239,6 +1304,20 @@ abstract class BaseDoubleStatisticTest<S extends DoubleStatistic & StatisticAccu
return actual;
}
+ /**
+ * Assert the computation of the statistic from the specified range of values.
+ *
+ * @param values Values.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
+ */
+ final void assertStatistic(double[] values, int from, int to) {
+ final double expected = create(Arrays.copyOfRange(values, from, to)).getAsDouble();
+ final double actual = create(values, from, to).getAsDouble();
+ Assertions.assertEquals(expected, actual,
+ () -> String.format("%s : [%d, %d) %s", statisticName, from, to, format(values)));
+ }
+
/**
* Assert the computation of the statistic using the
* {@link StatisticAccumulator#combine(StatisticResult) combine} method.
diff --git a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/DoubleStatisticsTest.java b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/DoubleStatisticsTest.java
index ac3f97d..ec75569 100644
--- a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/DoubleStatisticsTest.java
+++ b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/DoubleStatisticsTest.java
@@ -31,6 +31,7 @@ import java.util.function.Supplier;
import java.util.function.ToDoubleFunction;
import java.util.stream.IntStream;
import java.util.stream.Stream;
+import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.statistics.distribution.DoubleTolerances;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
@@ -53,6 +54,8 @@ import org.junit.jupiter.params.provider.MethodSource;
class DoubleStatisticsTest {
/** Empty statistic array. */
private static final Statistic[] EMPTY_STATISTIC_ARRAY = {};
+ /** The number of random permutations to perform. */
+ private static final int RANDOM_PERMUTATIONS = 5;
/** The test data. */
private static List<TestData> testData;
@@ -104,6 +107,13 @@ class DoubleStatisticsTest {
long size() {
return size;
}
+
+ /**
+ * @return the values as a single array
+ */
+ double[] toArray() {
+ return TestHelper.concatenate(values);
+ }
}
/**
@@ -275,6 +285,32 @@ class DoubleStatisticsTest {
assertStatistics(stats, data, builder::build, ExpectedResult::getArray);
}
+ /**
+ * Test the {@link DoubleStatistics} when data is passed as a range of {@code double[]} of values.
+ */
+ @ParameterizedTest
+ @MethodSource(value = {"streamTestData"})
+ final void testArrayRange(EnumSet<Statistic> stats, TestData data) {
+ // Test full range
+ final double[] values = data.toArray();
+ assertStatistics(stats, values, 0, values.length);
+ if (values.length == 0) {
+ // Nothing more to do
+ return;
+ }
+ // Test half-range
+ assertStatistics(stats, values, 0, values.length >> 1);
+ assertStatistics(stats, values, values.length >> 1, values.length);
+ // Random range
+ final long[] seed = TestHelper.createRNGSeed();
+ final UniformRandomProvider rng = TestHelper.createRNG(seed);
+ for (int repeat = RANDOM_PERMUTATIONS; --repeat >= 0;) {
+ final int i = rng.nextInt(values.length);
+ final int j = rng.nextInt(values.length);
+ assertStatistics(stats, values, Math.min(i, j), Math.max(i, j));
+ }
+ }
+
/**
* Assert the computed statistics match the expected result.
*
@@ -320,6 +356,35 @@ class DoubleStatisticsTest {
});
}
+ /**
+ * Assert the computation of the statistics from the specified range of values
+ * matches the computation using a copy of the range.
+ *
+ * @param stats Statistics that are computed.
+ * @param data Test data.
+ * @param from Inclusive start of the range.
+ * @param to Exclusive end of the range.
+ */
+ private static void assertStatistics(EnumSet<Statistic> stats, double[] data, int from, int to) {
+ final DoubleStatistics expected = DoubleStatistics.of(stats, Arrays.copyOfRange(data, from, to));
+ final DoubleStatistics statistics = DoubleStatistics.ofRange(stats, data, from, to);
+ Assertions.assertEquals(expected.getCount(), statistics.getCount(), "Count");
+ final EnumSet<Statistic> computed = EnumSet.copyOf(stats);
+ stats.forEach(s -> computed.addAll(coComputed.get(s)));
+
+ // Test if the statistics are correctly identified as supported
+ EnumSet.allOf(Statistic.class).forEach(s -> {
+ final boolean isSupported = computed.contains(s);
+ Assertions.assertEquals(isSupported, statistics.isSupported(s),
+ () -> stats + " isSupported -> " + s.toString());
+ if (isSupported) {
+ // Test individual values
+ Assertions.assertEquals(expected.getAsDouble(s), statistics.getAsDouble(s),
+ () -> stats + " getAsDouble -> " + s.toString());
+ }
+ });
+ }
+
/**
* Add all the {@code values} to an aggregator of the {@code statistics}.
*
@@ -404,6 +469,30 @@ class DoubleStatisticsTest {
Assertions.assertThrows(NullPointerException.class, () -> DoubleStatistics.of(s3, null));
}
+ @Test
+ void testOfSetRangeThrows() {
+ final double[] data = {};
+ final EnumSet<Statistic> s1 = EnumSet.noneOf(Statistic.class);
+ Assertions.assertThrows(IllegalArgumentException.class, () -> DoubleStatistics.ofRange(s1, data, 0, data.length));
+ final EnumSet<Statistic> s2 = null;
+ Assertions.assertThrows(NullPointerException.class, () -> DoubleStatistics.ofRange(s2, data, 0, data.length));
+ final EnumSet<Statistic> s3 = EnumSet.of(Statistic.MIN);
+ Assertions.assertThrows(NullPointerException.class, () -> DoubleStatistics.ofRange(s3, null, 0, 0));
+ }
+
+ /**
+ * Test the {@link DoubleStatistics#ofRange(Set, double[], int, int)} method throws with an invalid range.
+ */
+ @ParameterizedTest
+ @MethodSource(value = {"org.apache.commons.statistics.descriptive.TestData#arrayRangeTestData"})
+ final void testArrayRangeThrows(int from, int to, int length) {
+ final EnumSet<Statistic> statistics = EnumSet.of(Statistic.MIN);
+ final double[] values = new double[length];
+ Assertions.assertThrows(IndexOutOfBoundsException.class,
+ () -> DoubleStatistics.ofRange(statistics, values, from, to),
+ () -> String.format("range [%d, %d) in length %d", from, to, length));
+ }
+
@Test
void testBuilderThrows() {
Assertions.assertThrows(IllegalArgumentException.class, () -> DoubleStatistics.builder());
diff --git a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/GeometricMeanTest.java b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/GeometricMeanTest.java
index 73d445f..1bb43ba 100644
--- a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/GeometricMeanTest.java
+++ b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/GeometricMeanTest.java
@@ -39,6 +39,11 @@ final class GeometricMeanTest extends BaseDoubleStatisticTest<GeometricMean> {
return GeometricMean.of(values);
}
+ @Override
+ protected GeometricMean create(double[] values, int from, int to) {
+ return GeometricMean.ofRange(values, from, to);
+ }
+
@Override
protected double getEmptyValue() {
return Double.NaN;
diff --git a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/KurtosisTest.java b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/KurtosisTest.java
index 752edb0..355d3f9 100644
--- a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/KurtosisTest.java
+++ b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/KurtosisTest.java
@@ -42,6 +42,11 @@ final class KurtosisTest extends BaseDoubleStatisticTest<Kurtosis> {
return Kurtosis.of(values);
}
+ @Override
+ protected Kurtosis create(double[] values, int from, int to) {
+ return Kurtosis.ofRange(values, from, to);
+ }
+
@Override
protected double getEmptyValue() {
return Double.NaN;
diff --git a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/MaxTest.java b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/MaxTest.java
index 7f7c7c2..60d6191 100644
--- a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/MaxTest.java
+++ b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/MaxTest.java
@@ -36,6 +36,11 @@ final class MaxTest extends BaseDoubleStatisticTest<Max> {
return Max.of(values);
}
+ @Override
+ protected Max create(double[] values, int from, int to) {
+ return Max.ofRange(values, from, to);
+ }
+
@Override
protected double getEmptyValue() {
return Double.NEGATIVE_INFINITY;
diff --git a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/MeanTest.java b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/MeanTest.java
index 5094773..0d89001 100644
--- a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/MeanTest.java
+++ b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/MeanTest.java
@@ -40,6 +40,11 @@ final class MeanTest extends BaseDoubleStatisticTest<Mean> {
return Mean.of(values);
}
+ @Override
+ protected Mean create(double[] values, int from, int to) {
+ return Mean.ofRange(values, from, to);
+ }
+
@Override
protected double getEmptyValue() {
return Double.NaN;
diff --git a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/MinTest.java b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/MinTest.java
index c948678..dd7bebf 100644
--- a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/MinTest.java
+++ b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/MinTest.java
@@ -36,6 +36,11 @@ final class MinTest extends BaseDoubleStatisticTest<Min> {
return Min.of(values);
}
+ @Override
+ protected Min create(double[] values, int from, int to) {
+ return Min.ofRange(values, from, to);
+ }
+
@Override
protected double getEmptyValue() {
return Double.POSITIVE_INFINITY;
diff --git a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/ProductTest.java b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/ProductTest.java
index c8ac527..867808a 100644
--- a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/ProductTest.java
+++ b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/ProductTest.java
@@ -36,6 +36,11 @@ final class ProductTest extends BaseDoubleStatisticTest<Product> {
return Product.of(values);
}
+ @Override
+ protected Product create(double[] values, int from, int to) {
+ return Product.ofRange(values, from, to);
+ }
+
@Override
protected double getEmptyValue() {
return 1;
diff --git a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/SkewnessTest.java b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/SkewnessTest.java
index 6f021d8..fd55d13 100644
--- a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/SkewnessTest.java
+++ b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/SkewnessTest.java
@@ -42,6 +42,11 @@ final class SkewnessTest extends BaseDoubleStatisticTest<Skewness> {
return Skewness.of(values);
}
+ @Override
+ protected Skewness create(double[] values, int from, int to) {
+ return Skewness.ofRange(values, from, to);
+ }
+
@Override
protected double getEmptyValue() {
return Double.NaN;
diff --git a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/StandardDeviationTest.java b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/StandardDeviationTest.java
index dc24949..a071d16 100644
--- a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/StandardDeviationTest.java
+++ b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/StandardDeviationTest.java
@@ -43,6 +43,11 @@ final class StandardDeviationTest extends BaseDoubleStatisticTest<StandardDeviat
return StandardDeviation.of(values);
}
+ @Override
+ protected StandardDeviation create(double[] values, int from, int to) {
+ return StandardDeviation.ofRange(values, from, to);
+ }
+
@Override
protected double getEmptyValue() {
return Double.NaN;
diff --git a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/StatisticsTest.java b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/StatisticsTest.java
index f939a16..6da8384 100644
--- a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/StatisticsTest.java
+++ b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/StatisticsTest.java
@@ -20,8 +20,12 @@ package org.apache.commons.statistics.descriptive;
import java.util.function.DoubleConsumer;
import java.util.function.IntConsumer;
import java.util.function.LongConsumer;
+import java.util.stream.Stream;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
/**
* Test for {@link Statistics} utilities.
@@ -113,4 +117,30 @@ class StatisticsTest {
Assertions.assertEquals(y, v1[0]);
Assertions.assertEquals(y, v2[0]);
}
+
+ @ParameterizedTest
+ @MethodSource
+ void testCheckFromToIndex(int from, int to, int length) {
+ Assertions.assertThrows(IndexOutOfBoundsException.class, () -> Statistics.checkFromToIndex(from, to, length));
+ }
+
+ static Stream<Arguments> testCheckFromToIndex() {
+ final Stream.Builder<Arguments> builder = Stream.builder();
+ // fromIndex < 0
+ builder.add(Arguments.of(-1, 10, 10));
+ builder.add(Arguments.of(Integer.MIN_VALUE, 10, 10));
+ builder.add(Arguments.of(Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE));
+ // fromIndex > toIndex
+ builder.add(Arguments.of(2, 1, 10));
+ builder.add(Arguments.of(20, 10, 10));
+ builder.add(Arguments.of(0, -1, 10));
+ // toIndex > length
+ builder.add(Arguments.of(0, 11, 10));
+ builder.add(Arguments.of(0, Integer.MAX_VALUE, Integer.MAX_VALUE - 1));
+ // length < 0
+ builder.add(Arguments.of(0, 1, -1));
+ builder.add(Arguments.of(0, 1, Integer.MIN_VALUE));
+ builder.add(Arguments.of(0, Integer.MAX_VALUE, Integer.MIN_VALUE));
+ return builder.build();
+ }
}
diff --git a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/SumOfCubedDeviationsTest.java b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/SumOfCubedDeviationsTest.java
index 4acb46d..80c9f4d 100644
--- a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/SumOfCubedDeviationsTest.java
+++ b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/SumOfCubedDeviationsTest.java
@@ -48,6 +48,13 @@ final class SumOfCubedDeviationsTest extends BaseDoubleStatisticTest<SumOfCubedD
return new SumOfCubedDeviationsWrapper(SumOfCubedDeviations.of(values));
}
+ @Override
+ protected SumOfCubedDeviationsWrapper create(double[] values, int from, int to) {
+ // Add range checks here to pass the range validation tests
+ Statistics.checkFromToIndex(from, to, values.length);
+ return new SumOfCubedDeviationsWrapper(SumOfCubedDeviations.ofRange(values, from, to));
+ }
+
@Override
protected double getEmptyValue() {
return Double.NaN;
diff --git a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/SumOfFourthDeviationsTest.java b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/SumOfFourthDeviationsTest.java
index bf44a6b..21899ae 100644
--- a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/SumOfFourthDeviationsTest.java
+++ b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/SumOfFourthDeviationsTest.java
@@ -32,11 +32,11 @@ import org.apache.commons.statistics.distribution.DoubleTolerances;
* the algorithm on an array is not high precision.
*
* <p>Note that the output value is always positive and so does not
- * suffer as much from cancellation effects observed in the sum of cubed
- * deviations. However the sum of cubed deviation is used during the
+ * suffer as much from cancellation effects observed in the sum of Fourth
+ * deviations. However the sum of Fourth deviation is used during the
* updating and combine methods so errors can propagate. The test
* tolerances are higher than the first two moments, and lower than
- * the sum of cubed deviations.
+ * the sum of Fourth deviations.
*/
final class SumOfFourthDeviationsTest extends BaseDoubleStatisticTest<SumOfFourthDeviationsWrapper> {
@@ -55,6 +55,13 @@ final class SumOfFourthDeviationsTest extends BaseDoubleStatisticTest<SumOfFourt
return new SumOfFourthDeviationsWrapper(SumOfFourthDeviations.of(values));
}
+ @Override
+ protected SumOfFourthDeviationsWrapper create(double[] values, int from, int to) {
+ // Add range checks here to pass the range validation tests
+ Statistics.checkFromToIndex(from, to, values.length);
+ return new SumOfFourthDeviationsWrapper(SumOfFourthDeviations.ofRange(values, from, to));
+ }
+
@Override
protected double getEmptyValue() {
return Double.NaN;
@@ -100,11 +107,11 @@ final class SumOfFourthDeviationsTest extends BaseDoubleStatisticTest<SumOfFourt
TestData.momentTestData().forEach(x -> builder.accept(addCase(x)));
// The value 2^1023 will overflow the sum of squared deviations
builder.accept(addCase(0, 0, 0, 0x1.0p1023));
- // The value 2^500 will overflow the sum of cubed deviations but not
+ // The value 2^500 will overflow the sum of Fourth deviations but not
// the sum of squared deviations
builder.accept(addCase(0, 0, 0, 0x1.0p500));
// The value 2^300 will overflow the sum of fourth deviations
- // but not the sum of cubed deviations
+ // but not the sum of Fourth deviations
builder.accept(addCase(0, 0, 0, 0x1.0p300));
return builder.build();
}
diff --git a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/SumOfLogsTest.java b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/SumOfLogsTest.java
index df785b3..c109d64 100644
--- a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/SumOfLogsTest.java
+++ b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/SumOfLogsTest.java
@@ -37,6 +37,11 @@ final class SumOfLogsTest extends BaseDoubleStatisticTest<SumOfLogs> {
return SumOfLogs.of(values);
}
+ @Override
+ protected SumOfLogs create(double[] values, int from, int to) {
+ return SumOfLogs.ofRange(values, from, to);
+ }
+
@Override
protected double getEmptyValue() {
return 0;
diff --git a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/SumOfSquaresTest.java b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/SumOfSquaresTest.java
index 69eb99c..94acd1a 100644
--- a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/SumOfSquaresTest.java
+++ b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/SumOfSquaresTest.java
@@ -36,6 +36,11 @@ final class SumOfSquaresTest extends BaseDoubleStatisticTest<SumOfSquares> {
return SumOfSquares.of(values);
}
+ @Override
+ protected SumOfSquares create(double[] values, int from, int to) {
+ return SumOfSquares.ofRange(values, from, to);
+ }
+
@Override
protected double getEmptyValue() {
return 0;
diff --git a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/SumTest.java b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/SumTest.java
index d8e439c..94a1555 100644
--- a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/SumTest.java
+++ b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/SumTest.java
@@ -37,6 +37,11 @@ final class SumTest extends BaseDoubleStatisticTest<Sum> {
return Sum.of(values);
}
+ @Override
+ protected Sum create(double[] values, int from, int to) {
+ return Sum.ofRange(values, from, to);
+ }
+
@Override
protected double getEmptyValue() {
return 0;
diff --git a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/TestData.java b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/TestData.java
index 9a7f482..2c81820 100644
--- a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/TestData.java
+++ b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/TestData.java
@@ -17,6 +17,7 @@
package org.apache.commons.statistics.descriptive;
import java.util.stream.Stream;
+import org.junit.jupiter.params.provider.Arguments;
/**
* Utility class which provides the data for tests in {o.a.c.s.descriptive} module.
@@ -52,4 +53,26 @@ final class TestData {
new double[10]
);
}
+
+
+ /**
+ * Stream the arguments to test creation methods with an invalid array range.
+ * Arguments are [from, to, length].
+ *
+ * @return the stream
+ */
+ static Stream<Arguments> arrayRangeTestData() {
+ final Stream.Builder<Arguments> builder = Stream.builder();
+ // fromIndex < 0
+ builder.add(Arguments.of(-1, 10, 10));
+ builder.add(Arguments.of(Integer.MIN_VALUE, 10, 10));
+ // fromIndex > toIndex
+ builder.add(Arguments.of(2, 1, 10));
+ builder.add(Arguments.of(20, 10, 10));
+ builder.add(Arguments.of(0, -1, 10));
+ // toIndex > length
+ builder.add(Arguments.of(0, 11, 10));
+ builder.add(Arguments.of(0, 1, 0));
+ return builder.build();
+ }
}
diff --git a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/VarianceTest.java b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/VarianceTest.java
index a529e33..1391f48 100644
--- a/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/VarianceTest.java
+++ b/commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/VarianceTest.java
@@ -44,6 +44,11 @@ final class VarianceTest extends BaseDoubleStatisticTest<Variance> {
return Variance.of(values);
}
+ @Override
+ protected Variance create(double[] values, int from, int to) {
+ return Variance.ofRange(values, from, to);
+ }
+
@Override
protected double getEmptyValue() {
return Double.NaN;