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

Python百分位计算代码异常:输入最大值90时结果应为100%却错误

百分位数计算代码的错误排查与修复

你编写的Python代码用于计算百分位数,但输出结果明显不符合预期。例如输入low=50、lower_quartile=65、mean=70、median=71、upper_quartile=80、high=90、value=90时,代码返回51.233333333333334,而该值的百分位应为100%,其他输入也存在类似问题。

原代码如下:

low=int(input("enter low"))
lower_quartile=int(input("lower_quartile"))
mean=int(input("mean"))
median=int(input("median"))
upper_quartile=int(input("upper_quartile"))
high=int(input("high"))
value=int(input("value"))


def calculate_percentile(low, lower_quartile, mean, median, upper_quartile, high, value):
    # Calculate the interquartile range (IQR)
    iqr = upper_quartile - lower_quartile

    # Calculate the distance between the mean and the median in terms of the number of IQRs
    distance = (mean - median) / iqr

    # Calculate the distance between the given value and the median in terms of the number of IQRs
    value_distance = (value - median) / iqr

    # Calculate the percentile based on the given formula
    if value >= median:
        percentile = 50 + value_distance + (distance / 2)
    else:
        percentile = 50 + value_distance - (distance / 2)

    return percentile

test1=calculate_percentile(low, lower_quartile, mean, median, upper_quartile, high, value)
print(test1)

代码核心问题

  • 未使用边界值low和high:代码完全忽略了输入的最小值low和最大值high,导致当value等于high时,无法映射到100%的百分位。
  • 自定义公式偏离百分位数逻辑:百分位数的本质是数据在整体分布中的累积占比,而当前公式基于mean和median的IQR距离计算,完全脱离了这个核心逻辑。比如测试用例中mean=70小于median=71,导致distance为负数,最终计算结果严重偏小。
  • 缺失区间映射逻辑:没有划分数据分布的区间(如0-25%对应low到下四分位、25-50%对应下四分位到中位数等),无法根据value所在区间合理计算百分位。

修复方案

正确思路是根据value所在的区间,线性映射对应的百分位范围:

low=int(input("enter low: "))
lower_quartile=int(input("lower_quartile: "))
median=int(input("median: "))
upper_quartile=int(input("upper_quartile: "))
high=int(input("high: "))
value=int(input("value: "))


def calculate_percentile(low, lower_quartile, median, upper_quartile, high, value):
    if value <= low:
        return 0.0
    elif value <= lower_quartile:
        # 映射0%-25%区间
        return 25 * (value - low) / (lower_quartile - low)
    elif value <= median:
        # 映射25%-50%区间
        return 25 + 25 * (value - lower_quartile) / (median - lower_quartile)
    elif value <= upper_quartile:
        # 映射50%-75%区间
        return 50 + 25 * (value - median) / (upper_quartile - median)
    elif value <= high:
        # 映射75%-100%区间
        return 75 + 25 * (value - upper_quartile) / (high - upper_quartile)
    else:
        return 100.0

test1=calculate_percentile(low, lower_quartile, median, upper_quartile, high, value)
print(test1)

测试你给出的输入时,这段代码会返回100.0,符合预期。

内容的提问来源于stack exchange,提问作者E K

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 12:12:30