Calculate 95th percentile in Ruby?

Viewed 10144

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.

4 Answers

This is the method I developed in my own statistical library:

def quantiles(data, probs=[0.25, 0.50, 0.75])
  values = data.sort

  probs.map do |prob|
    h = 1 + (values.count - 1) * prob
    mod = h % 1
    (1 - mod) * values[h.floor - 1] + (mod) * values[h.ceil - 1]
  end
end

If you just want one quantile, then do quantiles(data, [0.95]).

Related