Skip to content

Commit aa22fd2

Browse files
committed
Clamp exponential histogram percentiles to min/max
1 parent 64b8574 commit aa22fd2

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

libs/exponential-histogram/src/main/java/org/elasticsearch/exponentialhistogram/ExponentialHistogramQuantile.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ public class ExponentialHistogramQuantile {
3434
* It returns the value of the element at rank {@code max(0, min(n - 1, (quantile * (n + 1)) - 1))}, where n is the total number of
3535
* values and rank starts at 0. If the rank is fractional, the result is linearly interpolated from the values of the two
3636
* neighboring ranks.
37+
* The result is clamped to the histogram's minimum and maximum values.
3738
*
3839
* @param histo the histogram representing the distribution
3940
* @param quantile the quantile to query, in the range [0, 1]
@@ -67,7 +68,7 @@ public static double getQuantile(ExponentialHistogram histo, double quantile) {
6768
} else {
6869
result = values.valueAtPreviousRank() * (1 - upperFactor) + values.valueAtRank() * upperFactor;
6970
}
70-
return removeNegativeZero(result);
71+
return removeNegativeZero(Math.clamp(result, histo.min(), histo.max()));
7172
}
7273

7374
private static double removeNegativeZero(double result) {

libs/exponential-histogram/src/test/java/org/elasticsearch/exponentialhistogram/QuantileAccuracyTests.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,21 @@ public void testNoNegativeZeroReturned() {
6363
assertThat(median, equalTo(0.0));
6464
}
6565

66+
public void testPercentilesClampedToMinMax() {
67+
ExponentialHistogram histogram = createAutoReleasedHistogram(
68+
b -> b
69+
.scale(0)
70+
.setNegativeBucket(1, 1)
71+
.setPositiveBucket(1, 1)
72+
.max(0.00001)
73+
.min(-0.00002)
74+
);
75+
double p01 = ExponentialHistogramQuantile.getQuantile(histogram, 0.01);
76+
double p99 = ExponentialHistogramQuantile.getQuantile(histogram, 0.99);
77+
assertThat(p01, equalTo(-0.00002));
78+
assertThat(p99, equalTo(0.00001));
79+
}
80+
6681
public void testUniformDistribution() {
6782
testDistributionQuantileAccuracy(new UniformRealDistribution(new Well19937c(randomInt()), 0, 100));
6883
}

0 commit comments

Comments
 (0)