double quantile(vector<double>&x, double q)
{
assert(q >= 0.0 && q <= 1.0);
const int n = x.size();
double id = (n-1)*q;
int lo = floor(id);
int hi = ceil(id);
double qs = x[lo];
double h = (id-lo);
return (1.0 - h) * qs + h * x[hi];
}
vector<double> z{1,2,3,4,5,6,7,8};
cout << quantile(z, 0.25) << endl;
cout << quantile(z, 0.5) << endl;
//0.75 ...
R语言quantile()
函数验证,结果相同。