lost_in_the_source
lost_in_the_source

Reputation: 11237

Argument out of range exception thrown

I saw this function on Percentile calculation, so I copied it and pasted it into the compiler, and it gives me an OutOfRange exception at

        else
        {
            int k = (int)n;
            double d = n - k;
            return sequence[k - 1] + d * (sequence[k] - sequence[k - 1]);//EXCEPTION
        }

What could be the source of the problem, and how do I solve it?

Function:

 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]);
    }
}

Upvotes: 0

Views: 349

Answers (2)

tinstaafl
tinstaafl

Reputation: 6948

As was mentioned, the function is designed to work with values between 0 and 1. Restricting the input should correct the problem.

 public double Percentile(double[] sequence, double excelPercentile)
 {
    //if(excelPercentile > 1)
        //excelPercentile = 1;
    //else if(excelPercentile < 0)
        //excelPercentile = 0;
    //Depending on how you validate the input you can assume that it's a whole number percentage.  Then you only need to check for the number to be between 0 and 100
    if(excelPercentile > 100)
       excelPercentile = 100;
    else if(excelPercentile < 0)
       excelPercentile = 0;
    excelPercentile /= 100;
    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]);
    }
}

Upvotes: 1

TGH
TGH

Reputation: 39248

The issue is that k is a number larger than the number of items in the array.

Upvotes: 2

Related Questions