通过直接应用定义(您可以在您链接的页面中找到)
// `xs` must be sorted
double percentile(double [] xs, int p) {
// The sorted elements in X are taken as the 100(0.5/n)th, 100(1.5/n)th, ..., 100([n – 0.5]/n)th percentiles.
int i = (int) (p * xs.length / 100.0 - 0.5);
// Linear interpolation uses linear polynomials to find yi = f(xi), the values of the underlying function
// Y = f(X) at the points in the vector or array x. Given the data points (x1, y1) and (x2, y2), where
// y1 = f(x1) and y2 = f(x2), linear interpolation finds y = f(x) for a given x between x1 and x2 as follows:
return xs[i] + (xs[i + 1] - xs[i]) * (p / 100.0 - (i + 0.5) / xs.length) / ((i + 1.5) / xs.length - (i + 0.5) / xs.length);
}
使用该页面上的示例
double [] xs1 = new double[] {6.0753, 8.6678, 0.4823, 6.7243, 5.6375, 2.3846, 4.1328, 5.6852, 12.1568, 10.5389};
Arrays.sort(xs1);
double r = percentile(xs1, 42);
System.out.println("Result: " + r);
System.out.println("Error: " + Math.abs(r - 5.6709));
你得到
Result: 5.67089
Error: 9.999999999621423E-6