@@ -19,8 +19,19 @@ import kotlin.reflect.typeOf
19
19
private val logger = KotlinLogging .logger { }
20
20
21
21
/* *
22
- * p-quantile: the k'th q-quantile, where p = k/q.
22
+ * Returns the p-quantile: the k'th q-quantile, where p = k/q.
23
23
*
24
+ * When [method] is a [QuantileEstimationMethod.Selecting] method,
25
+ * [this] can be a sequence with any self-comparable type.
26
+ * The returned value will be selected from the sequence.
27
+ *
28
+ * Otherwise, when [method] is a [QuantileEstimationMethod.Interpolating] method,
29
+ * [this] can only be a sequence with primitive number types.
30
+ * The returned value will be [Double].
31
+ *
32
+ * Nulls are not allowed. If NaN is among the values, it will be returned.
33
+ *
34
+ * @see QuantileEstimationMethod
24
35
*/
25
36
internal fun <T : Comparable <T >> Sequence<Any>.quantileOrNull (
26
37
p : Double ,
@@ -55,7 +66,12 @@ internal fun <T : Comparable<T>> Sequence<Any>.quantileOrNull(
55
66
}
56
67
57
68
// propagate NaN to return if they are not to be skipped
58
- if (type.canBeNaN && ! skipNaN && any { it.isNaN }) return Double .NaN
69
+ if (type.canBeNaN && ! skipNaN && any { it.isNaN }) {
70
+ // ensure that using a selecting quantile estimation method always returns the same type as the input
71
+ if (type == typeOf<Float >() && method is QuantileEstimationMethod .Selecting ) return Float .NaN
72
+
73
+ return Double .NaN
74
+ }
59
75
60
76
val list = when {
61
77
type.canBeNaN -> filter { ! it.isNaN }
@@ -201,7 +217,6 @@ internal sealed interface QuantileEstimationMethod<Value : Comparable<Value>, In
201
217
return values.quickSelect(h)
202
218
}
203
219
}
204
-
205
220
}
206
221
207
222
// TODO add R2, R4, R5, R6, R9
@@ -227,7 +242,7 @@ internal sealed interface QuantileEstimationMethod<Value : Comparable<Value>, In
227
242
return values.quickSelect(floor(h).toInt() - 1 ) + (h - floor(h)) * (
228
243
values.quickSelect(ceil(h).toInt() - 1 ) -
229
244
values.quickSelect(floor(h).toInt() - 1 )
230
- )
245
+ )
231
246
}
232
247
}
233
248
}
0 commit comments