關於百分位數的算法實現

    最近做一個項目,用到五分位法,五分位數的確定是用到16、37、63、84這幾個百分位數,試驗了幾個程序,發現不同的算法結果還是有差別的,我們這裏要求用Excel的百分位數計算方法,還好通過網上找到了excel算法的介紹。這裏把實現的函數分享。第一個是百度介紹的算法,第二個是Excel的算法實現。

    private double evaluateSorted1(final double[] sorted, final double p) {
        double n = sorted.length;
        double pos = p * (n+1) / 100;
        if (pos < 1) { return sorted[0]; }
        if (pos >= n) { return sorted[sorted.length - 1];}
        double fpos = Math.floor(pos);
        int intPos = (int) fpos;
        double dif = pos - fpos;
        double lower = sorted[intPos-1];
        double upper = sorted[intPos];
        return lower + dif * (upper - lower);
    }
    private double evaluateSorted2(final double[] sorted, final double p) {
        double n = sorted.length;
        double pos = p * (n - 1) / 100;
        double fpos = Math.floor(pos);
        int intPos = (int) fpos;
        double dif = pos - fpos;
        double lower = sorted[intPos];
        double upper = sorted[intPos+1];
        return (1-dif)*lower + dif *(upper);
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章