I have written a method to calculate a given percentile for a set of numbers for use in an application I am building. Typically the user needs to know the 25th percentile of a given set of numbers and the 75th percentile.
My method is as follows:
#get number of items in array
return nil if array.empty?
#sort the array
#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
Arraydoes not exist,
nil, so your initial check for an empty
Arrayargument, because you are affecting the order of the items in the
Arrayin the code that called your method. Use
returnstatement on the last line is unnecessary in Ruby.
That said, the function that you wrote can be written much more tersely while still being readable.
def calculate_percentile(array, percentile) array.sort[(percentile * array.length).ceil - 1] end