アイテム数に基づくパーセンタイル
a = [1,2,3,4,5,6,10,11,12,13,14,15,20,30,40,50,60,61,91,99,120]
def percentile_by_count(array,percentile)
count = (array.length * (1.0-percentile)).floor
array.sort[-count..-1]
end
# 80th percentile (21 items*80% == 16.8 items are below; pick the top 4)
p percentile_by_count(a,0.8) #=> [61, 91, 99, 120]
値の範囲に基づくパーセンタイル
def percentile_by_value(array,percentile)
min, max = array.minmax
range = max - min
min_value = (max-min)*percentile + min
array.select{ |v| v >= min_value }
end
# 80th percentile (119 * 80% = 95.2; pick values above this)
p percentile_by_value(a,0.8) #=> [99, 120]
興味深いことに、ExcelのPERCENTILE
関数は60
80パーセンタイルの最初の値として返されます。この結果が必要な場合(制限の先端にあるアイテムを含める場合)は、.floor
上記をに変更し.ceil
ます。