Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate 95th percentile in Ruby?

Tags:

This question here does not seem to help: Calculating Percentiles (Ruby)

I would like to calculate 95th percentile (or, indeed, any other desired percentile) from an array of numbers. Ultimately, this will be applied in Rails to calculate distribution against a large number of records.

But, if I can determine how to accurately determine a given percentile from an array of numbers, I can take it from there.

Frankly, I am surprised that I haven't been able to find some sort of gem that would have such functions--I haven't found one yet.

Help is greatly appreciated.

like image 789
n8gard Avatar asked Aug 02 '12 19:08

n8gard


People also ask

What does 95th percentile mean on a graph?

So a 95th percentile tells you the value which is greater than or equal to 95% of your data.

How do you find a percentile using a histogram?

Divide the frequency for each bin by the total frequency. In the example: 5/50, 15/50, 20/50, 7/50 and 3/50. Divide 100 by the total frequency. In the example 100/50 = 2.

How do I find percentiles in Rstudio?

You find a percentile in R by using the quantiles function. It produces the percentage with the value that is the percentile. This is the default version of this function, and it produces the 0th percentile, 25th percentile, 50th percentile, 75th percentile, and 100th percentile.


1 Answers

If you want to replicate Excel's PERCENTILE function then try the following:

def percentile(values, percentile)     values_sorted = values.sort     k = (percentile*(values_sorted.length-1)+1).floor - 1     f = (percentile*(values_sorted.length-1)+1).modulo(1)          return values_sorted[k] + (f * (values_sorted[k+1] - values_sorted[k])) end  values = [1, 2, 3, 4] p = 0.95 puts percentile(values, p) #=> 3.85 

The formula is based on the QUARTILE method, which is really just a specific percentiles - https://support.microsoft.com/en-us/office/quartile-inc-function-1bbacc80-5075-42f1-aed6-47d735c4819d.

like image 93
Justin Ko Avatar answered Sep 21 '22 19:09

Justin Ko