n8g*_*ard 19 ruby algorithm math ruby-on-rails-3
这里的这个问题似乎没有帮助:计算百分位数(Ruby)
我想从一组数字中计算出第95百分位数(或者实际上,任何其他所需的百分位数).最终,这将在Rails中应用,以计算针对大量记录的分布.
但是,如果我可以确定如何从一组数字中准确地确定给定的百分位数,我可以从那里开始.
坦率地说,我很惊讶我找不到某种具有这种功能的宝石 - 我还没有找到它.
非常感谢帮助.
Jus*_* Ko 26
如果要复制Excel的PERCENTILE函数,请尝试以下操作:
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
Run Code Online (Sandbox Code Playgroud)
该公式基于QUARTILE方法,该方法实际上只是特定的百分位数 - http://support.microsoft.com/default.aspx?scid=kb;en-us;Q103493.
brg*_*brg 11
如果你对现有的宝石感兴趣,那么descriptive_statistics宝石是我迄今为止发现的percentile功能最好的.
IRB会议
> require 'descriptive_statistics'
=> true
irb(main):009:0> data = [1, 2, 3, 4]
=> [1, 2, 3, 4]
irb(main):010:0> data.percentile(95)
=> 3.8499999999999996
irb(main):011:0> data.percentile(95).round(2)
=> 3.85
Run Code Online (Sandbox Code Playgroud)
宝石的好处是它描述"我想要95%的数据"的优雅方式.
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]
Run Code Online (Sandbox Code Playgroud)
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]
Run Code Online (Sandbox Code Playgroud)
有趣的是,Excel的PERCENTILE函数60作为第80个百分位的第一个值返回.如果你想要这个结果 - 如果你想要一个项目落在限制的尖端 - 包括 - 然后改变.floor上面的.ceil.