Created
April 20, 2023 10:10
-
-
Save aartajew/84f5d934999fb02bec5f6b1e6ad72fd1 to your computer and use it in GitHub Desktop.
Scala > Calculate percentile
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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