用于计算百分位数的Ruby on Rails方法 - 可以重构吗?

sim*_*ung 2 ruby ruby-on-rails

我已经编写了一种方法来计算一组数字的给定百分位数,以便在我正在构建的应用程序中使用.通常,用户需要知道给定数字集和第75百分位数的第25百分位数.

我的方法如下:

def calculate_percentile(array,percentile)
 #get number of items in array
 return nil if array.empty?

 #sort the array
 array.sort!

 #get the array length
 arr_length = array.length

 #multiply items in the array by the required percentile (e.g. 0.75 for 75th percentile)
 #round the result up to the next whole number
 #then subtract one to get the array item we need to return
 arr_item = ((array.length * percentile).ceil)-1

 #return the matching number from the array
 return array[arr_item]

end
Run Code Online (Sandbox Code Playgroud)

这看起来提供了我期待的结果,但任何人都可以重构这个或提供一个改进的方法来返回一组数字的特定百分位数?

mol*_*olf 12

一些评论:

  • 如果a的特定索引Array不存在,[]则返回nil,因此Array不需要初始检查空.
  • 你不应该sort!Array说法,因为你正在影响着项目的顺序Array 在调用你的方法的代码.使用sort(不!)代替.
  • arr_length在分配后实际上并未使用.
  • 一个return最后一行语句是在Ruby中不必要的.
  • 百分位函数没有标准定义(可能存在许多带有舍入的细微差别),所以我只假设你如何实现它是你想要它的行为方式.因此,我无法真正评论逻辑.

也就是说,您编写的函数可以更简洁地编写,同时仍然可读.

def calculate_percentile(array, percentile)
  array.sort[(percentile * array.length).ceil - 1]
end
Run Code Online (Sandbox Code Playgroud)

  • 根据本书中的分位数公式http://books.google.de/books?id=23WegW6oZm4C&lpg=PA118&dq=empirisches+quantil&hl=de&pg=PA118&redir_esc=y#v=onepage&q=empirisches%20quantil&f=false,您的解决方案不是100%正确.如果array.length*percentile是N的元素,它们使用两个值的平均值.对于```a = [1,1,1,3,4,7,8,11,13,13]````` `calculate_percentile(a,0.3)```应该返回2而不是1(这是有道理的,因为你不能说a中30%的值低于1) (2认同)