Skip to content

Instantly share code, notes, and snippets.

@aartajew
Created April 20, 2023 10:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aartajew/84f5d934999fb02bec5f6b1e6ad72fd1 to your computer and use it in GitHub Desktop.
Save aartajew/84f5d934999fb02bec5f6b1e6ad72fd1 to your computer and use it in GitHub Desktop.
Scala > Calculate percentile
package util
object Percentile {
// @see http://commons.apache.org/proper/commons-math/javadocs/api-3.6/org/apache/commons/math3/stat/descriptive/rank/Percentile.html
def apply(array: Seq[Double], p: Int) = {
require(p > 0)
require(p <= 100)
require(array.nonEmpty)
val n = array.length
if (n == 1) {
array.head
} else {
val sorted = array.sorted
val pos = p * (n + 1) / 100.0
val posFloor = math.floor(pos).toInt
if (pos < 1) {
sorted.head
} else if (pos >= n) {
sorted.last
} else {
val lower = sorted(posFloor)
val upper = if (n > posFloor + 1) sorted(posFloor + 1) else sorted(posFloor)
val d = pos - posFloor
lower + d * (upper - lower)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment