I have an array containing anywhere from 10 000 to 50 000 elements, representing values at risk in stressed economies. I am interested in calculating the x-th quantile for this array, using an ordinary weighting.
Immediately getting to my question - is it possible to determine a quantile for a large unsorted array without first sorting and then simply indexing? Or perhaps implementing functionality while sorting to also determine some quantile? Speed is of the utmost importance in my case, but a slower method not relying on first sorting would also be interesting to me.
Doing so the conventional way has been quite simple, by first sorting the array and then building SetWeights()
to do a bit of simple interpolation (Alpha
is the desired quantile fraction)
protected sealed override void SetWeights()
{
double n = (NumberOfScenarios - 1) * Alpha + 1;
if (Math.Abs(n - 1d) < double.Epsilon)
{
Weights = new List<double> { 1.0 };
Indices = new List<int> { 0 };
}
else if (Math.Abs(n - NumberOfScenarios) < double.Epsilon)
{
Weights = new List<double> { 1.0 };
Indices = new List<int> { NumberOfScenarios - 1 };
}
else
{
int k = (int)n;
double d = n - k;
Weights = new List<double> { 1.0 - d, d };
Indices = new List<int> { k - 1, k };
}
}
And then calculating the quantile by taking the respective indices for the weights
public double Quantile(List<double> sortedScenarios)
{
var varEstimator = 0.0;
for (var i = 0; i < Indices.Count; ++i)
{
varEstimator += Weights[i] * sortedSequence[Indices[i]];
}
return varEstimator;
}