Skip to content

Instantly share code, notes, and snippets.

@misshie
Created April 16, 2024 05:56
Show Gist options
  • Save misshie/92010137c99d9c6cacca157dad63ebb9 to your computer and use it in GitHub Desktop.
Save misshie/92010137c99d9c6cacca157dad63ebb9 to your computer and use it in GitHub Desktop.
Calculate percentaile values in an array of float values
#!/usr/bin/env ruby
class Percentile
ROUND_DIGIT = 1
def pctile(data0)
return [] if data0.empty?
data = data0.map{|x|Integer(x.round(ROUND_DIGIT) * (10 ** ROUND_DIGIT))}
sorted_data = data.sort
index_sum = Hash.new(0)
count = Hash.new(0)
# calculate sum of index and count of each value
sorted_data.each_with_index do |value, index|
index_sum[value] += index
count[value] += 1
end
# calculate mean indice of each value
average_index = index_sum.map{|val, sum| [val , (sum.to_f / count[val])]}.to_h
# calculate perventiles of each value
data_percentile_ranks = data.map do |value|
percentile_rank = average_index[value] / (data.length - 1) * 100
[(value.to_f / (10 ** ROUND_DIGIT)), percentile_rank]
end
data_percentile_ranks
end
def run
pp pctile([3.14, 1.4142, 3.14159, 2.2362])
## => [[3.1, 83.33333333333334], [1.4, 0.0], [3.1, 83.33333333333334], [2.2, 33.33333333333333]]
end
end
if $0 == __FILE__
Percentile.new.run
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment