You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

2018年Ruby中计算百分位数的便捷gem及方法咨询

Hey there! Back in 2018, there were a couple of reliable Ruby gems and straightforward ways to calculate percentiles. Let me walk you through the most practical options:

1. descriptive_statistics

This gem was one of the go-to choices for descriptive stats in 2018—it’s packed with handy methods, including percentile calculation, and requires almost no setup beyond installation.

First, install the gem:

gem install descriptive_statistics

Then use it in your code:

require 'descriptive_statistics'

# Sample dataset
data = [12, 25, 30, 40, 18, 22, 50]

# Calculate specific percentiles
p50 = data.percentile(50) # Median
p90 = data.percentile(90)
p25 = data.percentile(25)

puts "25th percentile: #{p25}"
puts "50th percentile (median): #{p50}"
puts "90th percentile: #{p90}"

Under the hood, it uses a linear interpolation method consistent with common statistical practices, so you can trust the results for most use cases.

2. statistics2

Another solid option from 2018, this gem focuses specifically on statistical functions. Note that it expects your dataset to be sorted before calculating percentiles.

Install the gem first:

gem install statistics2

Here’s how to use it:

require 'statistics2'

# Make sure to sort your data first
sorted_data = [12, 25, 30, 40, 18, 22, 50].sort

# Calculate percentiles
p75 = Statistics2.percentile(sorted_data, 75)
puts "75th percentile: #{p75}"

It’s lightweight if you only need basic statistical functions without the extra features of descriptive_statistics.

Manual Implementation (No Gems Needed)

If you prefer to avoid adding a gem dependency, here’s a simple linear interpolation-based implementation that works well for most scenarios:

def calculate_percentile(data, percentile)
  sorted_data = data.sort
  n = sorted_data.length
  rank = (percentile / 100.0) * (n - 1)
  
  lower_index = rank.floor
  upper_index = rank.ceil
  
  if lower_index == upper_index
    sorted_data[lower_index]
  else
    sorted_data[lower_index] + (sorted_data[upper_index] - sorted_data[lower_index]) * (rank - lower_index)
  end
end

# Test it out
data = [12, 25, 30, 40, 18, 22, 50]
puts "95th percentile: #{calculate_percentile(data, 95)}"

This mimics the behavior of many statistical libraries and gives you full control over the calculation logic.

内容的提问来源于stack exchange,提问作者ZK Zhao

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 09:03:39