Percentile calculation

前端 未结 3 1623
庸人自扰
庸人自扰 2020-12-29 22:43

I want to mimic the Excel equivalent PERCENTILE function in C# (or in some pseudo code). How can I do that? The function should take two arguments where the fir

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-29 22:54

    I think Wikipedia page has formulas you need to write your own function...
    I tried this:

    public double Percentile(double[] sequence, double excelPercentile)
    {
        Array.Sort(sequence);
        int N = sequence.Length;
        double n = (N - 1) * excelPercentile + 1;
        // Another method: double n = (N + 1) * excelPercentile;
        if (n == 1d) return sequence[0];
        else if (n == N) return sequence[N - 1];
        else
        {
             int k = (int)n;
             double d = n - k;
             return sequence[k - 1] + d * (sequence[k] - sequence[k - 1]);
        }
    }
    

    EDITED after CodeInChaos comment:
    Excel uses a percentile value between 0 and 1 (so I changed my code to implement this with Wikipedia formulas) and the other method to calulate n (so I changed the commented one).

提交回复
热议问题