Search code examples
javaapache-commons

Apache Commons Math3 Percentile of Number


I'm trying to get the percentile of a particular number within a distribution using the Apache Commons Math3 library, and the Percentile class:

https://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/stat/descriptive/rank/Percentile.html

(I'm consuming this in Scala)

If I do:

new Percentile().evaluate(Array(1,2,3,4,5), 80)

Then I get 4 back. However, I want to go the other direction, and give 4 as the input, and get back 80 as the result, i.e., the percentile of a given number, not the number at a given percentile.

None of the methods on this class seem to fit or give the result I want. Am I misusing the class? Is there another class I should be using?


Solution

  • You can use an EmpiricalDistribution loaded with your base line values:

    @Test
    public void testCalculatePercentile() {
        //given
        double[] values = new double[]{1,2,3,4,5};
    
        EmpiricalDistribution distribution = new EmpiricalDistribution(values.length);
        distribution.load(values);
    
        //when
        double percentile = distribution.cumulativeProbability(4);
    
        //then
        assertThat(percentile).isEqualTo(0.8);
    }